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 !