0
\$\begingroup\$

I am making a Custom Editor for a type that includes a UnityEvent property.

I'm currently facing an issue in converting a SerializedProperty to get that UnityEvent.

Here is how I declare the event in the type I want to edit with this custom editor:

public class SomeComponent : MonoBehaviour {

    public UnityEngine.Events.UnityEvent EventToAdd;

    //...
}

And this is my Editor script

[CustomEditor(typeof(SomeComponent))]
public SomeComponentEditor : Editor {

    private SerializedProperty _Events;
    private void OnEnable()
    {
        _Events = serializedObject.FindProperty("EventToAdd");
    }


    public override void OnInspectorGUI()
    {
        TwitchTVGui TGUI = (TwitchTVGui)target;

        this.serializedObject.Update();
        EditorGUILayout.PropertyField(serializedObject.FindProperty("EventToAdd"), true);

        this.serializedObject.ApplyModifiedProperties();
    }
}

And then I need to get the UnityEvent out of the serializedObject _Events somehow

\$\endgroup\$
1
  • \$\begingroup\$ Have you tried serializedObject.FindProperty("EventToAdd").objectReferenceValue as UnityEvent? \$\endgroup\$ Feb 19 '19 at 12:14
1
\$\begingroup\$

Huh, I literally just had this problem and found this code over here, but it basically boils down to needing just this:

[Serializable] public class CustomEvent : UnityEvent { }

public CustomEvent myEvent = new CustomEvent();

Rename the class and field as you see fit. If you're going to use the same event in multiple script files, make it its own script, but having a micro-class for each one is fine too (it distinguishes that OnWidgetDoX and OnWidgetDoY are different events).

\$\endgroup\$
0
\$\begingroup\$

If I understand correctly, you are trying to serialize events so that they will show up in the inspector. You do not need to do that yourself.

Instead, just use UnityEngine.Events.UnityEvent, and it will be available in the inspector for you. This is simply a wrapper around standard C#.

public UnityEvent MyEvent;
\$\endgroup\$
3
  • \$\begingroup\$ First of all thank you for your answer.I am currently working on a custom editor for our game designer and for that I am using serializedProperties. I can access strings,ints & co , but not UnityEvent... \$\endgroup\$
    – US3L3SS
    Jan 15 '19 at 23:35
  • \$\begingroup\$ @US3L3SS if you add the above line of code, it will show up in the inspector. Is that what you are trying to do? \$\endgroup\$
    – Evorlor
    Jan 15 '19 at 23:49
  • \$\begingroup\$ No I want to get the UnityEvent proberty... \$\endgroup\$
    – US3L3SS
    Jan 16 '19 at 0:21

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.