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?
Answer by nTu4Ka · May 03, 2016 at 06:52 AM
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.
Answer by serious6 · Nov 09, 2016 at 03:32 PM
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!!
It's been a while. But from what I figured out: at this point AddListener(() => SetUIText("This is button number " + Name)
not value of Name is given to listener but reference to Name. Which means all instances of objects had a reference to one variable. At the end of loop value of variable was "Three". So actual value was "Three" on all game objects (since they hold reference to variable not value at the moment of instantiating)... Redefining variable each loop solved the issue.
@nTu4$$anonymous$$a Thanks, man! It's much clearer now!
Your answer
![](https://koobas.hobune.stream/wayback/20220612080035im_/https://answers.unity.com/themes/thub/images/avi.jpg)