Collection of Buttons - individual callbacks

Hello everyone,

I am facing a problem, where I have multiple Button references stored in an array and I would like to have an individual callback depending on the index of the button. My idea to do this was the following:

for (int i = 0; i < buttons.Length; i++)
{
    buttons[i].clicked += () => OnButtonClicked(i);
}

However, when any of the buttons get clicked then, the method is called with parameter i = buttons.Length.
Is there any solution for this?

Thank you!
Lukas

Hi!
This happens because you are using a lambda function that will capture the i variable.

To fix this, you will need to assign it to a local variable before using it in your lambda:

for (int i = 0; i < buttons.Length; i++)
{
    var index = i;
    buttons[index].clicked += () => OnButtonClicked(index);
}

Hope this helps!

Hi!

Thank you so much :slight_smile:
Again something learned about lambdas.

Hi,

what about, if I would like to remove this specific clicked event again? Or what if I would like to remove all clicked events? How can I do this?

If you want to remove the callback on the button, you can add the callbacks as method group:

void OnClick()
{
   // code goes here
}

// To add
button.clicked += OnClick;

// To Remove
button.clicked -= OnClick;

Now, this would lose the index argument.

If you want to remove all clicked event on a button, you can do button.clickable = null;.