Search Unity

Resolved Question with Populating Button Listener with For Loop

Discussion in 'Scripting' started by AhSai, May 24, 2023.

  1. AhSai

    AhSai

    Joined:
    Jun 25, 2017
    Posts:
    129
    I am populating my buttons array with the following code, all of the button clicks are printing the length of the array instead of individual index.

    Code (CSharp):
    1.         for (int i = 0; i < buttons.Length; i++)
    2.             buttons[i].onClick.AddListener(() => Debug.Log(i));
    Why does this happen?
     
  2. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,635
    Your loop is incrementing the value of i each time. Once the loop is complete then the value of i will be the same as the value of buttons.length. When you click the button, Debug.Log will show the value of i as it is now, not the value when the listener was assigned.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,700
    SisusCo, AhSai and kdgalla like this.
  4. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,329
    And this can be avoided by assigning
    i
    to a new variable which is declared inside the body of the for statement, and using this variable in the lambda expression instead.
    Code (CSharp):
    1. for(int i = 0; i < buttons.Length; i++)
    2. {
    3.    int index = i;
    4.    buttons[index].onClick.AddListener(() => Debug.Log(index));
    5. }