Search Unity

Which procedural button was clicked?

Discussion in 'Scripting' started by BlackArcane, Jul 1, 2015.

  1. BlackArcane

    BlackArcane

    Joined:
    Jun 26, 2011
    Posts:
    119
    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?


    Code (CSharp):
    1. for(int i = 0; i < currentPlayer.hand.Count; i++)
    2.         {
    3.             GameObject temp = GameObject.Instantiate(button);
    4.          
    5.             temp.GetComponentInChildren<Text>().text = currentPlayer.hand[i].name;
    6.             temp.GetComponent<Button>().onClick.AddListener(() => HandlePlayInput(i));
    7.             temp.transform.SetParent(container.transform);
    8.         }

    Code (CSharp):
    1. void HandlePlayInput(int index)
    2.     {
    3.         waiting = false;
    4.         currentPlayer.play(index);
    5.         ClearInput();
    6.     }
     
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    3,508
    Store i in a temporary variable:

    Code (csharp):
    1.  
    2. for(int i = 0; i < currentPlayer.hand.Count; i++)
    3. {
    4.     int temp = i;
    5.     GameObject temp = GameObject.Instantiate(button);
    6.  
    7.     temp.GetComponentInChildren<Text>().text = currentPlayer.hand[i].name;
    8.     temp.GetComponent<Button>().onClick.AddListener(() => HandlePlayInput(temp));
    9.     temp.transform.SetParent(container.transform);
    10. }
    More info on why here.
     
  3. BlackArcane

    BlackArcane

    Joined:
    Jun 26, 2011
    Posts:
    119
    Works like a charm, thank you! :)