Custom Event Handler in Inspector?

So in a UI Button, there’s a nice and handy OnClick field where you can add objects and a function attached to the object to call, so that when the button is pressed all of the functions in the OnClick will be called.

Is there a way where I can use this feature to store functions and have it so I can call a function that calls all of the stored functions? Something like

this.eventhandler.callAll();
1 Like

@wontonst Crikey - I hope it’s not too late to answer this, but I was hunting around to remind myself how to do this as it’s been a while and couldn’t remember the magic words. :slight_smile:

Anyway, it’s easily done:

using UnityEngine.Events;

public UnityEvent yourCustomEvent;

public void Foo() {
    // Trigger the event!
    yourCustomEvent.Invoke();
}

Here’s more info.

@sotirosn It works using Custom inspector. You just have to use serialized property EditorGUILayout.PropertyField (eventTest_Prop);

The Editor Script should looks like this:

    using UnityEngine;
    using UnityEditor;
        
        [CustomEditor(typeof(YourScriptName)), CanEditMultipleObjects]
        public class YourScriptNameEditor : Editor {
        
        	public SerializedProperty yourCustomEvent_Prop;
        
                void OnEnable () {
                     yourCustomEvent_Prop = serializedObject.FindProperty ("yourCustomEvent");
                }
    
                public override void OnInspectorGUI () {
                     EditorGUILayout.PropertyField (yourCustomEvent_Prop);

                     serializedObject.ApplyModifiedProperties ();
               }
            }

In my case works correctly the variant

public override void OnInspectorGUI()
{
    base.OnInspectorGUI();
    //EditorGUILayout.PropertyField(yourCustomEvent_Prop);
    serializedObject.ApplyModifiedProperties();
}

In other case the field in Inspector double.
And Don’t forget:

  • The script “YourScriptNameEditor” must be in folder Assets\Editor and named as “YourScriptNameEditor.cs”
  • In “typeof(YourScriptName)” - YourScriptName - name of script where you use the “yourCustomEvent”
  • “yourCustomEvent” - It’s the name of your event

all other can be unchangeable