0
\$\begingroup\$

I'm working on a point and click system in Unity and I have a contextual menu that appears when you right click on an object. In this menu, there's a button called "search" that moves the player to the object and opens a menu representing that object's contents. The Search Button calls a method that takes a gameobject as a parameter; in other words, the object that the player treats as the target to which it moves and then searches.

All of this is working just fine, but there's one problem: Currently I have two test containers, a crate and a barrel. The crate is the object that the button is taking as a parameter, so if I right click the barrel and select "search", the player will go to search the crate.

How do I dynamically change the gameobject target of the button so that the search button will know the correct object it should be targetting, I.E. whichever object the player right clicked?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Have a variable on the context menu or a selection manager that stores what object was right-clicked.

Set that variable when you run the code that shows the context menu.

When searching, don't call the player's search method directly. Ask the context menu to invoke the search (no arguments needed), and it can inject the target object into the call when it forwards it on to the player:

public class ContextMenu : MonoBehaviour {

    GameObject _contextMenuTarget;
    
    public void OpenContextMenuOn(GameObject target) {
        _contextMenuTarget = target;
        // Put code that shows the menu here.
    }
    
    public void InvokeSearch() {
         Player.Search(_contextMenuTarget);
    }    
}
\$\endgroup\$
1
  • \$\begingroup\$ Tried it and it worked. Wow, that feels really obvious now. Thanks! \$\endgroup\$ May 28, 2022 at 20:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .