UnityEvent Serialization Problem

Hello, I have an issue relating to using UnityEvents in a Custom Inspector.

I’ve managed to get it into some shorter code.

This is my script:

using UnityEngine;
using UnityEngine.Events;

public class Test : MonoBehaviour {

    public MyEvent myEvent;

    public class MyEvent : UnityEvent { }

On its own the script works as expected. But when using the Custom Inspector script bellow there is a problem.

using UnityEngine;
using UnityEngine.Events;
using UnityEditor;
using UnityEditor.SceneManagement;

public class TestEditor : Editor {

    public override void OnInspectorGUI() {
        GUILayout.Label("This is a label just to show the Custom Inspector is working.");
        Test myTarget = (Test)target;
        SerializedObject s = new UnityEditor.SerializedObject(myTarget);
        EditorGUILayout.PropertyField(s.FindProperty("myEvent"), true);
        if (EditorGUI.EndChangeCheck())

The problem is when entering a value for a static parameter into the Editor. For example, I can add a method to call such as ‘GameObject > int layer’ and enter a value like bellow.


Then I can click on another GameObject in the scene. When I go back to this script the value gets replaced with 0 (as bellow). I assume it is not being serialized somehow. But the default Unity Editor can serialize it so it must be possible. Is my code wrong?


Thank you

After some more googling I got there. It was just a little mistake in my code.

This line:

SerializedObject s = new UnityEditor.SerializedObject(myTarget);

means I am creating a new SerializedObject and the editor is serializing the UnityEvent to that object. It is not saving it to the actual SerializedObject the editor uses.

So it should be:

SerializedObject s = serializedObject;

Its been a long day :frowning: