简体   繁体   中英

UI Button.onClick handling multiple buttons via script

I'm loading and instantiating a Unity prefab that has UI objects in it (text, buttons) and want to assign the onClick handler for each found button via script ...

GameObject uiObj = ResourceUtil.InstantiatePrefab("Prefabs/UI/Main Menu UI", "UI");
uiObj.transform.SetParent(gameObject.transform, false);
Button[] buttons = uiObj.GetComponentsInChildren<Button>();
foreach (Button button in buttons)
{
    button.onClick.AddListener(() => OnUIButtonClick(button.name)); 
}

public void OnUIButtonClick(string buttonID)
{
    Log.Debug("OnUIButtonClick: " + buttonID);
}

However when clicking any of the buttons, only the ID of the last button is ever logged out. It seems that every button receives the same onClick handler assignment (which is the last in the iteration). How can I get it to work so that the onClick handler is assigned uniquely to every button?

I had a similar issue. I still do not fully understand why did it start working, probably it was some addressing issue on lower level or something, but solution was something like:

foreach (Button button in buttons)
{
    string _name = button.name;
    button.onClick.AddListener(() => OnUIButtonClick(_name)); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM