- Home /
adding event to EventTrigger on runtime
Hi, I have some issues with adding events to EventTrigger on runtime.
Here is my code:
int i = 0;
foreach(Transform x in myGameObject)
{Debug.Log(i);
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = EventTriggerType.PointerEnter;
entry.callback.AddListener((eventData) => {MyFunction(i);});
x.GetComponent<EventTrigger>().triggers.Add(entry);
i++;
}
public void MyFunction(int x)
{
Debug.Log(x);
}
The problem is that when i point at any UI object which was set-up this way Debug in MyFunction returns 10 (number of childs in myGameObject) but Debug in foreach shows all numbers from 0 to 9.
Does anyone know why this happens and what should I do to make my UI objects to call MyFunction with the variable I give them?
Answer by corn · May 22, 2016 at 09:50 AM
You need to make a local copy of i. When a closure references a local variable in its outer scope, it captures a reference to the variable, not the value contained in the variable.
int i = 0;
foreach (Transform x in myGameObject)
{
Debug.Log(i);
int j = i;
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = EventTriggerType.PointerEnter;
entry.callback.AddListener((eventData) => { MyFunction(j); });
x.GetComponent<EventTrigger>().triggers.Add(entry);
i++;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to access the Boolean for one object? 1 Answer
Error assigning to a variable 0 Answers