- Home /
Question by
unity_Js2-Edti_aeI3g · Jul 17, 2020 at 07:56 PM ·
c#scripting problembutton
Adding Listeners in for loop with a temporary variable doesn't work
I've been trying to figure this out for weeks. The name and text of each button are unique, but each listener outputs the same value. Am I capturing the variable wrong?
void Awake()
{
for (int i = 0; i < greetings.Length; i++)
{
//Instantiate the button
Vector3 offset = new Vector3(dialogueParent.transform.position.x, dialogueParent.transform.position.y + (textDistance * i), dialogueParent.transform.position.z);
GameObject buttonObject = Instantiate(statementButton, offset, Quaternion.identity, dialogueParent.transform);
//Set the buttons name
ResponseBox = buttonObject.transform.GetChild(0).GetComponent<Text>();
buttonObject.name = ("Button:" + i);
ResponseBox.text = greetings[i];
//Assign the temp variable and then assign the listener
int t = i;
Button butt = buttonObject.GetComponent<Button>();
butt.onClick.AddListener(() => Debug.Log(t));
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613003423im_/https://answers.unity.com/themes/thub/images/avi.jpg)