Hi,
I have a problem with the script below.
it’s simple function to assign Listerner with parameter to a list of button.
void SetupButton()
{
for (int i = 0; i < ButtonList.Count; i++)
{
ButtonList[i].onClick.AddListener(() => OnButton(i));
}
}
void OnButton(int i)
{
Debug.Log("Click on : " + i);
}
I have 5 buttons in the list. it should show the number 0, 1, 2, 3, 4 when clicking on each button.
but after run this code, no matter what button was clicked, it always return “Click on : 5”
it seem to use the last value of i to assign to all button’s parameter.
but if I did the hard code for each button like this
ButtonList[0].onClick.AddListener(() => OnButton(0));
ButtonList[1].onClick.AddListener(() => OnButton(1));
ButtonList[2].onClick.AddListener(() => OnButton(2));
ButtonList[3].onClick.AddListener(() => OnButton(3));
ButtonList[4].onClick.AddListener(() => OnButton(4));
now it’s working fine as expected.
Could someone please tell me why I can’t use the for-loop to assign parameter to onClick.AddListener() method?
Thanks in advance & best regards,
Bodin