- Home /
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 {
 
     [SerializeField]
     public MyEvent myEvent;
 
     [System.Serializable]
     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;
 
 [CustomEditor(typeof(Test))]
 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);
         s.Update();
         EditorGUI.BeginChangeCheck();
         EditorGUILayout.PropertyField(s.FindProperty("myEvent"), true);
         s.ApplyModifiedProperties();
         if (EditorGUI.EndChangeCheck())
         {
             EditorUtility.SetDirty(target);
             EditorSceneManager.MarkAllScenesDirty();
         }
     }
 }
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
Answer by the_genius · Sep 19, 2017 at 11:16 PM
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 :(
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                