Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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,326
    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:
    36,563
    SisusCo, AhSai and kdgalla like this.
  4. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,104
    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. }