Search code examples
unity-game-engineunity3d-ui

UI prefabs: buttons does not retain onclick() settings


I have a simple prefab, made by a prefab button and a panel. The button is placed inside the panel so it is a child of the panel. I did save the prefab and all is good.

Then, I did add a click event on the button; so I did add the gameobject where the script that I want to use is placed, and select the correct method to use. I did update the prefab and deleted it from the scene.

Now, when I instantiate this prefab in the scene with Resources.Load("myUIprefab"); it show correctly the panel, the button and the colors/settings.

But there is nothing connected to the click button itself; which result in the button doing nothing.

Isnt' a prefab, a way to save an object to be used at later time? In that case it should retain the click settings. Is this a bug or an unfortunate implementation of the new Unity UI system? Makes little sense to make a prefab out of a button or another GUI element, if then the click() or other delegate are not filled.


Solution

  • GameObjects that are stored in a prefab can only hold references to other objects inside that same prefab, or to other prefabs. This is true for object references, events, whatever.

    If you want the event to persist, you must have an event handler in the same prefab and have that called by your button. This can be a simple handler method that raises a standard .Net event when called (.Net events may be easier to use than Unity events).