ScriptableObject - Serialization and Delegates

Hey all

I’m writing a hierarchy of ScriptableObjects. I have chosen ScriptableObjects instead of simple classes because I want to take advantage of the serialization.

I use delegates to pass events up the hierarchy. An object in my hierarchy might look like:

public class Parent : ScriptableObject
{
    private Child m_Child;

    public SetChild(Child child)
    {
        this.Unsubscribe(this.m_Child);
        this.m_Child = child;
        this.Subscribe(this.m_Child);
    }

    protected virtual void Unsubscribe(Child child)
    {
        if (child == null)
            return;

        child.onSomeEvent -= this._ChildDidSomething;
    }

    protected virtual void Subscribe(Child child)
    {
        if (child == null)
            return;

        child.onSomeEvent += this._ChildDidSomething;
    }

    private void _ChildDidSomething(Child child, ChildDidSomethingArgs args)
    {
    }
}

Now, I need to make sure these delegates are still connected between sessions. Presumably they are not serialized by Unity (although the documentation is lacking a comprehensive list on what IS serializable).

If I were inheriting from MonoBehaviour I would simply do something like:

protected virtual void Awake()
{
    this.Unsubscribe(this.m_Child); // Incase we're already subscribed
    this.Subscribe(this.m_Child);
}

Though ScriptableObject does not have an Awake hook.

Is it possible to override some kind of deserialization method? It would be great if there was some kind of OnPostDeserialization method to take advantage of.

Thanks,
Ves

ScriptableObject has OnEnable and OnDisable (as does MonoBehaviour and EditorWindow) which can be used to setup event subscriptions.

@VesuvianPrime: See this answer to see how you could basically serialize delegates (make them survive assembly reloads). See uFAction for a full already-made solution for serializable and inspectable delegates.

@numberkruncher: That is true, however a lot of the times you need to wire up your delegate at edit time, and have its value persist and make it through to runtime so you have to serialize it somehow.