- Home /
Serialize UnityEvent for use in EditorWindow
I've been creating an editor tool, which keeps some data as ScriptableObject with HideFlags.HideAndDontSave. This way, the data survives a recompile and play mode.
Now I wanted to add delegates to use as callbacks between some of my data objects, but of course, those get garbage collected as soon as I enter play mode.
So I thought, why not just use UnityEvent and AddPersistentLister to create those events? Theoretically, they should be serialized correctly and survive play mode, but in fact, it doesn't work and I can't figure out why.
[System.Serializable]
public class MyEvent : UnityEvent<float> { }
public class MyWindow : EditorWindow
{
public MyData data;
void OnEnable()
{
hideFlags = HideFlags.HideAndDontSave;
if (data == null)
{
data = MyData.CreateInstance<MyData>();
data.callback = new MyEvent();
UnityEventTools.AddPersistentListener(data.callback, MyMethod);
}
}
public void MyMethod(float f)
{
Debug.Log(f);
}
public class MyData : ScriptableObject
{
public MyEvent callback;
void OnEnable()
{
hideFlags = HideFlags.HideAndDontSave;
}
}
}
As far as the documentation goes, this should work. My Window is a persistent ScriptableObject and is has a public field of a ScriptableObject derived type that is also persistent. This part serialized fine. The event is also a non-generic type and marked as serializable. I've used AddPersistentListener instead of AddListener, but it doesn't make any difference. In both cases, after play mode exit, the listener is removed.
I've done another test with a MonoBehaviour component on a GameObject in the scene and noticed the same thing. I can add listeners through the inspector and they persist as they should, but if I assign them at runtime in Start, they don't get saved.
What might I be missing?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Save/Load Animation State of Instantiated Prefabs 0 Answers
Serializabel class not updating 2 Answers