I’m attempting to add multiple buttons with a custom event listener in code, but the second button is overwriting the first. I’m using my own pooling setup, but I’ve determined that it is not the issue.
Here is the relevant code:
var buildables = new Dictionary<Subtypes, string>();
buildables.Add(Subtypes.Barracks, "Barracks");
buildables.Add(Subtypes.Brig, "Brig");
var tempInt = 0;
foreach (var button in buildables)
{
GameObject goButton = buttonPool.Add().gameObject;
goButton.transform.SetParent(BuildMenu, false);
goButton.transform.localScale = new Vector3(1, 1, 1);
goButton.transform.position = new Vector3(BuildMenu.transform.position.x, BuildMenu.transform.position.y - (tempInt * 50), BuildMenu.transform.position.z);
goButton.GetComponentInChildren<Text>().text = button.Value;
Button tempButton = goButton.GetComponent<Button>();
tempButton.onClick.AddListener(() => ButtonClicked(button.Key, tri));
tempInt++;
}
Whenever I click either barracks or brig, it builds barracks. I believe the issue lies in the assignment of goButton and/or tempButton as debugging shows them persisting through the foreach loop.
Thanks in advance.