[SOLVED] Assigning different actions on instantiated Prefabs

Hello Guys,
I’m trying to instantiate one button for every AudioFile in my array. My problem is that every button plays the same file and I don’t really know why.

Here a small Codesnippet of my For-Loop.

for (int i=0; i<audioFiles.Length; i++) {
GameObject button = (GameObject)Instantiate (buttonPrefab);
button.GetComponent<Button>().onClick.AddListener(
                () => {PlayAudio(i);}
            );
}

With 2 AudioFiles in use every Button get the Parameter “2”. But why? I’m looking for a small workaround now but what I don’t get is that i should never have the value 2?
Hope my explanation was clear enough.

Not sure, but you are using delegates in a loop

This can cause issues with the delegate taking the last value of the loop variable (in your example 2) .

Have you tried making a local copy of the value in the loop?

    for (int i=0; i<audioFiles.Length; i++) {
    GameObject button = (GameObject)Instantiate (buttonPrefab);
int temp = i;
    button.GetComponent<Button>().onClick.AddListener(
                    () => {PlayAudio(temp);}
                );
    }
1 Like

thanks for the fast answer! I’ll try this immediatly. :slight_smile:
But I still wonder why the last value is 2 when there is a “<” and not a “<=”.

EDIT: It worked! The temp variable solved it! Thanks a lot!