Search code examples
instantiationunity-game-engineeventtrigger

How do I add EventTriggers to Multiple instantiated prefabs from a list?


I have a prefab which I am spawning a dynamic amount of.

I want to attach an event trigger to each one of them, on pointerclick, to call a method accepting an int as parameter.

I have the following code which partly works, however the event added to each prefab uses the same parameter, even though they are given as beign different.

foreach (EasterEgg EE in AllEasterEggs.List)
{
    Transform x = Instantiate(EasterEggPrefab);
    ...
    EventTrigger.Entry Entry = new EventTrigger.Entry();
    Entry.eventID = EventTriggerType.PointerClick;
    Entry.callback.AddListener((eventData) => { EasterEggClicked(EE.ID); });

    x.GetChild(1).GetComponent<EventTrigger>().triggers.Add(Entry);
}

EE.Id on the first item will be 0, then it will be 1, then 2 etc. I have debugged to ensure that when it is adding the listener that EE.Id is the correct number, and this is true. The trigger is being added correctly.

However when I trigger the trigger (how to say that?), the parameter beign passed is always the parameter of the last item in that list. For example, if AllEasterEggs.List contains 5 elements, all elements will have a trigger on pointer click calling EasterEggClicked(4), whereas they should be EasterEggClicked(0) thru EasterEggClicked(4).


Solution

  • As a request, this is the answer:

    Instead of passing EE object to anonimous delegate, just store value of EE.ID before and pass this:

    foreach (EasterEgg EE in AllEasterEggs.List)
    {
        Transform x = Instantiate(EasterEggPrefab);
        ...
        EventTrigger.Entry Entry = new EventTrigger.Entry();
        Entry.eventID = EventTriggerType.PointerClick;
        int ID = EE.ID;
        Entry.callback.AddListener((eventData) => { EasterEggClicked(ID); });
    
        x.GetChild(1).GetComponent<EventTrigger>().triggers.Add(Entry);
    }