0

So, I worked on my shop system and I wanted to make it so that when the player presses the button, that button was selected (I need to know the id of button that I press)

void Awake()
{
    //Cycle through all the ShopItems
    for (int i = 0; i < shopItemsList.Count; i++)
    {
        go = Instantiate(ItemTemplate, ShopScrollView);
        go.GetComponent<Button>().onClick.AddListener(() => ItemButton(i));
        go.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = shopItemsList[i].itemName;

        if (!shopItemsList[i].isPurchased)
        {
            go.transform.GetChild(1).gameObject.SetActive(true);
        }
        else if (shopItemsList[i].isChosen)
        {
            go.GetComponent<Image>().color = new Color32(164, 0, 0, 255);
        }
            go.transform.GetChild(1).GetChild(0).GetComponent<TextMeshProUGUI>().txt = shopItemsList[i].price.ToString() + "$";
        }
    }


    void ItemButton(int itemName)
    {
        Debug.Log(itemName);
    }
}

So when I Press Play button in Unity all works fine (every item has its stats) but all buttons have the same value that equals to 12 (the last iteration of "for" cycle)

Ghost
  • 735
  • 5
  • 16
Stealthguy
  • 33
  • 5

1 Answers1

1

This is how captures and for loops works in C# (you can read more about it here or here for example). Introduce temporary variable, assign i to it and use it in lambda:

 for (int i = 0; i < shopItemsList.Count; i++)
    {
        var temp = i;
        go = Instantiate(ItemTemplate, ShopScrollView);
        go.GetComponent<Button>().onClick.AddListener(() => ItemButton(temp));
        ....
    } 
Guru Stron
  • 102,774
  • 10
  • 95
  • 132