Hey there,
I implemented a dynamic dropdown menu for my inventory system today and all is working well, however, I have run into an odd bug when assigning the listener for my buttons.
The dropdown item has 3 inactive buttons that are activated, text is changed, and listerner assigned when the dropdown is called on the appropriate item. The odd thing is that the SendMessage call I am using to add the listener seems to be assigning an incorrect function call seperate from the i iteration that it should be using. Hopefully, my code clears up my problem as it is difficult to explain.
public void ShowMenu(ClassItemUI targetItem)
{
_menuIsActive = true;
curParentItem = targetItem;
//ACTIVATE ALL APPROPRIATE BUTTONS
for (int i = 0; i < curParentItem.dropdownButtonNames.Length; i++)
{
print("Message: " + (i));
actionButtons[i].gameObject.SetActive(true);
//SET NAME & FUNCTION
actionButtons[i].GetComponentInChildren<TextMeshProUGUI>().text = curParentItem.dropdownButtonNames[i];
actionButtons[i].onClick.AddListener(() => curParentItem.SendMessage("UseButton" + (i)));
}
MenuPosition();
}
When I click on a button it prints the corresponding “UseButton” function. When I use an item with 2 buttons this the command log that I get in return:
Message: 0
Message: 1
Use Button 3
Use Button 3
The Use Button log should be “Use Button 0” followed by “Use Button 1”. It is as if the AddListener is using the total iterations in the for loop rather than the current.
Any help is greatly appreciated thanks!