- Home /
Issue with spawning buttons and assigning listeners
So, I'm creating a bunch of buttons and trying to give them all the same method on click but it should be different based on the key each button possesses. However, they all call the exact same key (which is the last one added). I am very confused at what's going on or why they all use the same same string. Anyone know what's going on with adding listeners in a for loop? Here's the code I call in start
public void populateVisibleNames() {
for(int i = 0; i<visibleNames.Count; i++)
{
Transform newButton = Instantiate(namePrefabButton) as Transform;
newButton.SetParent(buttonPanel.transform);
Button b = newButton.GetComponent<Button>();
b.onClick.AddListener(() => disablePanel(nameButton, visibleNames[i-1].ToString()));
newButton.GetChild (0).GetComponent<Text>().text = visibleNames[i].ToString();
nameButtons.Add(b);
newButton.gameObject.SetActive(true);
newButton.transform.localPosition = new Vector3(0,-i*30,0);
}
}
Thanks, not sure why you can't do it directly, but it worked. Thanks a bunch
Answer by digzou · Jun 11, 2015 at 12:30 PM
I was facing some similar issues recently. This is how I solved it. Save the name to a local variable and the use that variable.
for(int i = 0; i<visibleNames.Count; i++)
{
Transform newButton = Instantiate(namePrefabButton) as Transform;
newButton.SetParent(buttonPanel.transform);
Button b = newButton.GetComponent<Button>();
string btn_name = visibleNames[i-1].ToString();
b.onClick.AddListener(() => disablePanel(nameButton, btn_name));
newButton.GetChild (0).GetComponent<Text>().text = visibleNames[i].ToString();
nameButtons.Add(b);
newButton.gameObject.SetActive(true);
newButton.transform.localPosition = new Vector3(0,-i*30,0);
}
Here's the snippet if my code if it helps you by any chance :
if(!languagesSet){
foreach(LanguagePack lp in languageList){
GameObject langbtn = Instantiate(Resources.Load<GameObject>("LangButton"));
langbtn.transform.SetParent(GameObject.Find("VerticalPanel").transform);
langbtn.name = lp.Id;
langbtn.GetComponent<RectTransform>().localScale = Vector3.one;
langbtn.GetComponentInChildren<UnityEngine.UI.Text>().text = lp.Id;
string str = lp.Id;
langbtn.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => { changeLanguage(str);});
languagesSet=true;
}
}
Your answer
Follow this Question
Related Questions
Children of DualTouchControls prefab keep being forced to active 0 Answers
UI button mobile - want a button drag to register as a click 0 Answers
How to detect button presses and change child object text in the button's Parent Object script 0 Answers
Can't to get Button script from gameobject in unity 0 Answers
4.6 UI Check if a button and a in-game object are overlapping 0 Answers