Event listener on all instantiated buttons is the same

Hi,

I instantiate a number of buttons from prefab in a loop.

On each button an event listener is set with different parameter on each loop iteration.

The problem is - all resulting game objects have same parameter in the end. The last one.

GameObject ButtonParent;
string[] NameArray = new string[] {One, Two, Three};

foreach (string Name in NameArray) {
    ButtonParent = (GameObject)Instantiate(PrefabObject, Vector3.zero, Quaternion.identity);           
    ButtonParent.GetChild(0).GetComponent<Button>().onClick.AddListener(() => SetUIText("This is button number " + Name));
}

Following example will always show “This is button number Three” on any button click.

Am I missing something?

Do different objects share same event listener or something?

Omg.
It seems that not value but reference was used by listener.
So on click event the value was the same on all listeners.

Adding

string Value = Name;
ButtonParent.GetChild(0).GetComponent<Button>().onClick.AddListener(() => SetUIText("This is button number " + Value));

solved the problem.

Hi @nTu4Ka, I had the same problem and I could solve it your way, but I don’t understand what’s going on. Could you (or anybody else) please explain me? Thanks!!