Procedural Context Menu (Point and Click

Hi!

I’m making a point and click game, and I want to design a context menu that opens when clicking on an item in the inventory bar. (ignore the ugliness, it’s all for testing at the moment)

So far, i have managed to instantiate a prefab UI image with a script “ContextMenu” (bottom left blank UI Image).

I want the context menu to instantiate specific buttons based on available interactions with the right clicked inventory item.

For example, with the current parts in the inventory bar, you can “Use” them, and “Examine” them. They have a script on them that implements the interfaces IUsable and IExaminable, each with a method I want to hook up to a button via scripting.

I would like to avoid writing code such as

 public void Setup(InventoryItem item)
    {
     var examinableItem = item as IExaminable;
     //create a button
     button1.GetComponent<Button>().onClick.AddListener(() => 
     examinableItem.Examine());

     var useableItem = item as IUsable;
     //create a button
     button2.GetComponent<Button>().onClick.AddListener(() => 
     examinableItem.Use());
    }

Do you have any suggestions?

Thanks for your time!

Right now what I have is this:

 public void SetupContextMenu(InventoryItem item)
    {
        IUsable usableItem = item as IUsable;

        if (usableItem != null)
        {
            SetupButton(() => usableItem.Use(playerController), "Use");
        }

        IExaminable examinableItem = item as IExaminable;

        if (examinableItem != null)
        {
            SetupButton(() => examinableItem.Examine(playerController), "Examine");
        }
    }

    void SetupButton(UnityAction method, string buttonName)
    {
        GameObject buttonPrefab = Resources.Load<GameObject>(Path);
        GameObject button = Instantiate(buttonPrefab, GetComponentInChildren<Image>().transform);
        button.GetComponent<Button>().onClick.AddListener(method);
        button.GetComponent<Button>().GetComponentInChildren<Text>().text = buttonName;
    }

Which works I guess, but isn’t optimal. Then again, there aren’t going to be many many options for the context menu, maybe around 5 or so. But I do always like to program things in the most scalable way possible.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms