I’m trying to make a UnityEvent with no params call a function with one parameter. The parameter is the index of the component in an array.
I’ve simplify my code to the just important, buggy, part:
arrayComps*.OnClickEvent.AddListener(() => Debug.Log("Event i:" + i));*
At the moment I have an array with 9 items, and all my results are:
Event i: 9
I also tried with anonymous delegate with the same results.
Idk if what I want is possible. Is it?
Thanks for your help
Your lambda expression references a variable from an outer scope. That means it becomes a closure and has to close over that variable. You most likely use a for loop and your “i” variable is your for loop variable. This means each closure you create closes over the same variable. Since after the loop has completed the variable i contains the value 9, each closure sees the same value.
This is not Unity specific but the general behaviour of closures since closures do close over variables, not over values.
The solution is to create a local variable inside your loop and close over that variable. Each iteration the compiler will create a seperate closure context:
for(int i = 0; i < arrayComps.Length; i++)
int index = i;
arrayComps*.OnClickEvent.AddListener(() => Debug.Log("Event i:" + index)); // close over "index"*