0

I would like to add onClick listeners to my buttons in Unity, C#. I have an array of these buttons. I am trying to loop through that array, and for each button, I am adding an onClick listener which calls a function that takes an index parameter. In that function, I print out the paramater that the function has received. However, when I click on one of these buttons, I get 10 as an output every time.

for(int i = 0; i < roleButtons.Length; ++i) {
    roleButtons[i].onClick.AddListener(delegate { changeEquipment(i); });
}

void changeEquipment(int index) {
    Debug.Log(index); //Here I got 10 as an output after every single click.
}
  • You need to copy the variable `i` locally – Cid Nov 07 '20 at 14:28
  • This is called a 'closure'. You pass the 'i' variable as a closure which means all buttons wil receive the same value from 'i' which after the for loop has the value 10. – Paul Sinnema Nov 07 '20 at 15:04

0 Answers0