Home > database >  How do I detect what GameObject of a List (which is displayed) was clicked and reference it in Unity
How do I detect what GameObject of a List (which is displayed) was clicked and reference it in Unity

Time:09-13

I am currently building a shop for a game. The shop items are stored in a list and displayed in order on the screen. I want to detect, what object of that list was clicked and access it's values to display them on the screen. Any idea how I can do that?

CodePudding user response:

Make it a button and make a script which you use that button to buy the item

CodePudding user response:

You will need to dynamically create the UI buttons/(item icons) for each element.

Your code may look something like this:

Transform ButtonPrefab;

...

void PopulateShopItems(List<Item> itemList) 
{
    foreach(var item in itemList)
    {
        Transform buttonTransform = Instantitate(ButtonPrefab);
        
        // Set the position of the button
        ...
        
        // Get the button component (which should be on the button prefab)
        Button button = buttonTransform.GetComponent<Button>();
        
        // Add a listener for the button
        button.onClick.AddListener(delegate{BuyItem(item);});
    }   
}


void BuyItem(Item item)
{
    // Do the buy item things
}

The idea behind it being you have a button prefab that will acts as an icon/button for a specific item. And if you click that button it will call the function you wanted it to.


As an extra thing, you can add a script to your button prefeab that makes everything a bit easier.

[RequireComponent(typeof(Button))]
public ItemButton 
{
    Button button;
    
    void Start()
    {
        button = GetComponent<Button>();
    }
    
    public void SetButtonProperties(Item item)
    {
        // Example Code -- May not work 100%;
        button.GetComponentInChild<Text>().text = item.name;
        ...

    }
}
  • Related