Assign a method to the OnClick event in a Button prefab.

Hello,
So I have a button prefab that I want to call a function (to play an audio effect) for its OnClick event.

I define the function in a monobehaviour, but, how could I assign it to the OnClick event of the button prefab? Because the monobehaviour isn’t available in all scenes where the button appears.

A first solution I found would to use a ScriptableObject that would be available across the whole project, but I don’t think it is a proper/best solution.

Any advice?

Thanks in advance!

One way is to directly assign the listener via script, like the example here: Unity - Scripting API: UI.Button.onClick

Personally, I prefer to simply assign the OnClick in the inspector to a function that is somewhere on a script in the prefab itself, and have that script do something dynamic like finding on object via tag or using a singleton pattern.

3 Likes

Hi, I implemented a solution bassed on your suggestion and seems to work pretty good.
Thanks!

After checking documentation… wouldn’t it be more interesting to use scriptableobject or, at least, to combine with it?
e.g.: If I instantiate 10 prefab buttons, I will have x10 text components.

Using scriptable objects you would have 10 buttons with x10 references to 1 scriptable object (1 text component) with a text field.

From doc:
“Every time you instantiate that Prefab, it will get its own copy of that data. Instead of using the method, and storing duplicated data, you can use a ScriptableObject to store the data and then access it by reference from all of the Prefabs. This means that there is one copy of the data in memory.”

Bu şekilde çözüldü teşekkürler.