Which procedural button was clicked?

Hello everyone. Moving from the old UI system to the new one was a breeze and the benefits are a lot. I can’t however think of a proper way to deal with procedurally generated buttons. If my understanding is correct, creating them in a for loop and adding the counter as a parameter to the delegate will always return the last value of the counter, not the current one. Am I doing something wrong?

for(int i = 0; i < currentPlayer.hand.Count; i++)
        {
            GameObject temp = GameObject.Instantiate(button);
          
            temp.GetComponentInChildren<Text>().text = currentPlayer.hand[i].name;
            temp.GetComponent<Button>().onClick.AddListener(() => HandlePlayInput(i));
            temp.transform.SetParent(container.transform);
        }
void HandlePlayInput(int index)
    {
        waiting = false;
        currentPlayer.play(index);
        ClearInput();
    }

Store i in a temporary variable:

for(int i = 0; i < currentPlayer.hand.Count; i++)
{
    int temp = i;
    GameObject temp = GameObject.Instantiate(button);

    temp.GetComponentInChildren<Text>().text = currentPlayer.hand[i].name;
    temp.GetComponent<Button>().onClick.AddListener(() => HandlePlayInput(temp));
    temp.transform.SetParent(container.transform);
}

More info on why here.

Works like a charm, thank you! :slight_smile: