onClick.AddListener() didn't work as expected.

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

Replace line 5 with these two lines:

            int j = i;
            ButtonList[i].onClick.AddListener(() => { OnButton(j); });

It’s called ‘closure’, google ‘c# unity closure’ and you’ll find lots of tutorials.

4 Likes

Hi Kamilche_,

thank you very much! I will try that.

That’s work! thank you very much.
actually what I done is add this line

int j = i;

and used j instead of i for the next line.

1 Like