- Home /
Dynamic Anonymous Delegates/Lambda On UntyEvent
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[i].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?
Any thoughts?
Thanks for your help
Answer by Bunny83 · Mar 30, 2018 at 01:45 AM
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[i].OnClickEvent.AddListener(() => Debug.Log("Event i:" + index)); // close over "index"
}
Your answer
Follow this Question
Related Questions
Events/delegates not working on Android (working in Unity player though) 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers