- Home /
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();
Answer by nockieboy · Sep 03, 2015 at 05:41 PM
@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. :)
Anyway, it's easily done:
using UnityEngine.Events;
public UnityEvent yourCustomEvent;
public void Foo() {
// Trigger the event!
yourCustomEvent.Invoke();
}
Unfortunately this doesn't work if the object is being handle by a custom inspector. I imagine there is a EditorGUILayout.EventField(yourCustomEvent)
but I cannot find one.
Answer by Pitrizzo · Aug 16, 2016 at 05:04 PM
@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 ();
}
}
Works like a charm. For some other examples from Unity check this out: property-drawers-custom-inspectors
Don't to forget to call base.OnInspectorGUI(); if you do the above. Else all the other SerializeFields are not exposed to the editor. So:
public override void OnInspectorGUI() {
base.OnInspectorGUI();
EditorGUILayout.PropertyField(onPublishProperty);
serializedObject.Apply$$anonymous$$odifiedProperties();
}
Answer by DSivtsov · Nov 20, 2020 at 05:33 AM
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