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.
}