1
\$\begingroup\$

I know that UnityEvents display themselves automatically with the default inspector.

But what if you create a custom inspector by extending the Editor class? The fields don't draw automatically since they're overridden by the custom editor.

How can I write my custom Editor class, so that it displays my UnityEvent fields in exactly the same way as the default inspector?

For example, here is the UnityEvent method selection widget for the Button component using its default inspector:

Button Inspector showing UnityEvent widget

\$\endgroup\$
1
\$\begingroup\$

This has worked just fine in my tests:

[CustomEditor(typeof(TypeWithCustomEvent))]
public class TypeWithCustomEventEditor : Editor {

    public override void OnInspectorGUI() {    
        // Find the property corresponding to the UnityEvent we want to edit.
        var prop = serializedObject.FindProperty("myEvent");

        // Draw the Inspector widget for this property.
        EditorGUILayout.PropertyField(prop, true);

        // Commit changes to the property back to the component we're editing.
        serializedObject.ApplyModifiedProperties();
    }
}
\$\endgroup\$
  • \$\begingroup\$ I have done that but I havent tried to test it, though, because I was sure it wouldn't work. For example, with booleans or other values you have to assign .boolValue ... It's interesting I will try and let you know. I have also found a better approach to create the behaviour I wanted, the inheritance from Button class is completely unnecessary, so it can be just another component. \$\endgroup\$ – Candid Moon _Max_ Nov 17 '17 at 8:25
  • \$\begingroup\$ Yeah, this was unfamiliar to me too at first, since I haven't done much with PropertyField. Apparently it saves its changes right into the SerializedProperty you pass it (and its child tree, potentially) rather than using the return value to express them. \$\endgroup\$ – DMGregory Nov 17 '17 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.