Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lambda expression cannot hold parameter

[SerializeField] List<Button> Buttons;
void Start()
{
    for (int i = 0; i < Buttons.Count; i++)
    {
        Buttons[i].onClick.AddListener(() => DoThing(i));// can't hold i variable
        //when click the each button result is always 3
        // i want 0,1,2
        print(i); // 0,1,2
    }
}
public void DoThing(int value)
{
    print(value);
}

I want to use i as parameter of a button click event action but each button always prints 3. Instead of using i Buttons[i].onClick.AddListener(() => DoThing(2)) is working fine. how use i as parameter

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In your code, DoThing will capture the variable i (and not its value) and will only get the value of i when you invoke onClick.

Copy the value of a changing variable to the scope where the closure is defined

[SerializeField] List<Button> Buttons;

void Start()
{
    for (int i = 0; i < Buttons.Count; i++)
    {
        var iLocal = i;
        Buttons[i].onClick.AddListener(() => DoThing(iLocal));
    }
}

public void DoThing(int value)
{
    print(value);
}

This fix makes sure that when you get the context where the action was created, iLocal will hold the value corresponding to the index of the button in the list.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading