0
votes

In Unity I want to create my UI in this way:

  1. Create a UI gameobject with all texts/buttons/etc. laid out in it.
  2. Save that object as a prefab.
  3. 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?

1

1 Answers

0
votes

Assigning listeners to Button components was done correctly. I've tested your code and it works for me. Weard, maybe problem is somewhere else. Do you have EventSystem added to your scene?