[Godot 4] Why is this C# lambda code not working?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ondesic

I found that I can use a lambda bind a parameter to a function, but I am having a problem. I have 3 buttons in an array called “btns”. I want each button to send a different number to the ButtonDown() function.

If I individually assign each button it will work:

btns[0].ButtonDown += () => _btnDown(0);
btns[1].ButtonDown += () => _btnDown(1);
btns[2].ButtonDown += () => _btnDown(2);

However, if I use a “for” loop to do the same thing, the code doesn’t work. it assigns “4” to every buttons ButtonDown event:

for (int i = 0; i < btns.Length; i++)
        btns[i].ButtonDown += () => _btnDown(i);

Shouldn’t this work?

:bust_in_silhouette: Reply From: juppi

When the for loop finishes, i has the number of the arrays length.
That means it will call these methods with the final value of i.

So using a temp value will get around this:

for (int i = 0; i < btns.Length; i++)
    int num = i;
    btns[i].ButtonDown += () => _btnDown(num);