- Home /
AddListener in a loop only running once
Greetings.
I am quite a beginner at Unity and at C#, but that's actually the first time I need to ask a question. So I have this bit of code :
public class InvWindow : MonoBehaviour
{
GameObject itemButton;
Inventory playerInventory;
private void Start()
{
itemButton = this.transform.Find("ItemButton").gameObject;
playerInventory = this.transform.parent.parent.Find("MainBody").GetComponent<Inventory>();
// Creation of the contents
int margin = 0;
foreach (string key in playerInventory.inventory.Keys) {
GameObject instance = Instantiate(itemButton, this.transform); // create a entry
Vector3 position = instance.transform.localPosition;
// change game object name to make it unique _ DOES NOT FIX THE ISSUE
instance.name = ("itemButton_" + margin);
// These four lines move the button down each time one is created
position.y =+ margin;
instance.transform.localPosition = position;
instance.SetActive(true);
margin =+ 30;
// Set appropriate name
instance.transform.Find("Text").GetComponent<Text>().text = key;
// Create button interaction
instance.GetComponent<Button>().onClick.AddListener(() => ItemClicked(key));
}
}
private void ItemClicked(string name)
{
Debug.Log("Brrrt! Clicked on " + name);
}
}
It is supposed to read from a HashTable, and create a functional inventory window by instantiating the prefab button "itemButton" for each item. Currently the table has two entries, and everything works fine, two buttons are created with the proper renaming. However the AddListener bit only works for the first button (the argument is passed correctly), the second one is not clickable at all.
I've seen similar problems on Internet, but nothing I tried fixed this. What am I doing wrong?
Your answer
Follow this Question
Related Questions
Where is the best place to use delegate call back without calling it in Update function? 1 Answer
Subscribing to an event via non-mono script. 0 Answers
Listen for clicks outside of unity application 0 Answers
Button AddListener during runtime pointing to another GameObject? 1 Answer
ArgumentException for UnityEvent 0 Answers