- Home /
Weird behaviour when trying to dynamically create buttons
Hello, I am facing a weird behavior when I am trying to dynamically add a "prefab" in my UI. To be more specific, I have created a prefab with some texts, some images and a button. Alse I have a List nameList. I am trying to dynamically create/add this prefab in my UI as many times as list's size.
for(int i = 0; i<nameList.Count; i++)
{
GameObject go = Instantiate(myPrefab) as GameObject;
go.transform.SetParent(myContainer);
name.text = nameList[i];
myInteger.text = i + " ";
int tempInteger = i; // so the myInteger.text and the button MUST have the same integer assigned!!!
Button tempButton = go.GetComponentInChildren<Button>();
tempButton.onClick.AddListener(() => myFunc(tempInteger));
}
public void myFunc(int tempInteger)
{
Debug.Log(tempInteger);
}
So, the gameobjects are creating and everything looks fine but when I click on the button the integer that has been assigned to it is wrong!
Also the LAST element from the list appears FIRST and the rest in the "propper position". So I have something like this:
[UI, Console]
5( myInteger.text), "0" (from the Debug.Log on myFunc )
0( myInteger.text), "1" (from the Debug.Log on myFunc )
1( myInteger.text), "2" (from the Debug.Log on myFunc )
2( myInteger.text), "3" (from the Debug.Log on myFunc )
3( myInteger.text), "4" (from the Debug.Log on myFunc )
4( myInteger.text), "5" (from the Debug.Log on myFunc )
Any ideas?
Your answer
Follow this Question
Related Questions
Passing through a GameObject/Function to a button's OnClick 1 Answer
My onclick action listeners I attach to my buttons as I instantiate them only work once 1 Answer
button.onClick.AddListener(method); NOT Working 1 Answer
Button.onClick.AddListener inconsistent 0 Answers
AddListener() Javascript 2 Answers