Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Collection of Buttons - individual callbacks

Discussion in 'UI Toolkit' started by LuKrO2011, May 16, 2022.

  1. LuKrO2011

    LuKrO2011

    Joined:
    Mar 6, 2020
    Posts:
    3
    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:

    Code (CSharp):
    1. for (int i = 0; i < buttons.Length; i++)
    2. {
    3.     buttons[i].clicked += () => OnButtonClicked(i);
    4. }
    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
     
  2. martinpa_unity

    martinpa_unity

    Unity Technologies

    Joined:
    Oct 18, 2017
    Posts:
    370
    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:

    Code (CSharp):
    1. for (int i = 0; i < buttons.Length; i++)
    2. {
    3.     var index = i;
    4.     buttons[index].clicked += () => OnButtonClicked(index);
    5. }
    Hope this helps!
     
  3. LuKrO2011

    LuKrO2011

    Joined:
    Mar 6, 2020
    Posts:
    3
    Hi!

    Thank you so much :)
    Again something learned about lambdas.
     
  4. LuKrO2011

    LuKrO2011

    Joined:
    Mar 6, 2020
    Posts:
    3
    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?
     
  5. martinpa_unity

    martinpa_unity

    Unity Technologies

    Joined:
    Oct 18, 2017
    Posts:
    370
    If you want to remove the callback on the button, you can add the callbacks as method group:
    Code (CSharp):
    1. void OnClick()
    2. {
    3.    // code goes here
    4. }
    5.  
    6. // To add
    7. button.clicked += OnClick;
    8.  
    9. // To Remove
    10. 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;
    .