- Home /
Button.OnClic.AddListener(delegate{method(object);}), wrong object sent
Hi ! I have an array of object of type Station, and I'd like to generate one button per item, then when the button is clicked I want to do something with the corresponding Station object. Here's a simplified version of relevant code :
foreach(Station s in stations)
{
GameObject b = Instantiate(buttonTemplate) as GameObject;
//...
Button b2 = b.GetComponent<Button>();
b2.onClick.AddListener(delegate {setStation(s);});
}
//and further down
public void setStation(Station s)
{
Debug.Log(s.name);
}
No matter what button I clic, setStation is always called with the last element of the array, not the one corresponding to the button I clicked.
Why is this happening, and what is the correct way to get the result I want ? Thanks for help !
Thanks that fixed it ! Can you sugest some reading so I can understand why ?
It's called a closure. A quick look found me this page here:
Answer by hexagonius · Feb 28, 2015 at 11:30 AM
Create a local Station variable in the foreach and pass it into the setStation() method.
Just read this blog post of Eric Lippert. Note that Eric is one of those who developed and designed the C# compiler for $$anonymous$$icrosoft. Also note that "C# 5" doesn't apply to Unity / $$anonymous$$ono in general.
This is a quite common problem and got asked several times before, see my answer over here.
I had a same problem. but your solution is worked. Thanks, mate.
I up-voted this answer.
Cheers