In Unity I want to create my UI in this way:
- Create a UI gameobject with all texts/buttons/etc. laid out in it.
- Save that object as a prefab.
- Load the prefab in at runtime and instantiate it, and add it as a child to a parent UI container object.
Now the problem is how do I assign event handlers for the buttons at runtime (since the assigned ones in the inspector get removed when making a prefab).
I'm trying this code but it's not working:
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));
}
private void OnUIButtonClick(Button button)
{
Log.Debug("OnUIButtonClick: " + button);
}
The UI prefab is loaded and added successfully but the buttons don't act on clicking them. Does somebody know how to do this successfully?