How to: select a callback function for your script, from the editor.

I really wanted a way to pick a callback function for my script, from within the editor. But, I didn’t want to add an event trigger component, and even if I did, I’d have to bastardize one of the existing events for my custom purposes.

I searched around first, to no avail. Since I found nothing, I figured I’d post what I eventually figured out here.

First we add:

#using UnityEngine.EventSystems;
#using UnityEngine.Events;

to the top of the monobehavior’s script

Then add a public memeber to the class:

public EventTrigger.TriggerEvent customCallback;

After compiling, we can now see the option to select a (list of) functions, in the editor. It looks just like what you see when working with an event trigger component. But, notice these are INSIDE the monobehavior component, titled “customCallback”, and will not be executed unless we say so.

Elsewhere in the class we want to actually execute this function, which we do like this:

customCallback.Invoke(eventData);

As far as how to get, eventData, it doesn’t really matter. You can pass along a received event’s eventData, or create one yourself like this:

BaseEventData eventData= new BaseEventData(EventSystem.current);
eventData.selectedObject=this.gameObject;

Note whatever custom callback function we want to select in the editor, must be of the form:

void foo(BaseEventData);
8 Likes

I’ve been googled around. Finally found this thread.
Awesome share! Thank you!

Oh great, glad it was helpful! Any feedback/suggestions on making it better/easier to understand?

There’s been a big thread on it, but in case you didn’t see it, the UnityEvent class does pretty much the same thing.

Oh, that’s nice! UnityEvent doesn’t require you get or generate any BaseEventData, and lets you call multiple functions at once by adding “listeners”. I like it, thanks Baste!

Then again, I guess not having to pass the BaseEventData could also be a disadvantage since you no longer have ANY parameters.

UnityEvent seems good too!
Both EventTrigger.TriggerEvent and UnityEvent will be very useful for me.

By the way, I’m implementing a “focus” system, and these callbacks are used for OnFocus and OnUnfocus.

You can also build a full blown custom inspector using reflection. You can chain methods together and step through there results. Or you can find methods that are nested inside members of other types.

It’s mostly overkill for all practical purposes. But it was fun to build.

Playing around with this again… I finally noticed UnityEvents this time around…Unity - Scripting API: UnityEvent<T0>
This version DOES let you pass a parameter, of any Type. Just don’t miss this bottom of this page, or it wont show up in the inspector (Unity - Manual: UnityEvents)

1 Like