ScriptableObject and Serialization

When developing DanmakuX, I've noticed that Unity3D does not serialize polymorphic data correctly. When you have a base pointer to a derived instance inside the component, only the base class will be serialized/deserialized when the scene is loaded.

For example, I have a base class and a derived class like this

[System.Serilizable]
class Base { 
    public string name;
};

[System.Serializable]
class Derived: Base {
    public int data;
};

And I store them in my component

class MyComponenet: MonoBehaviour {
    // won't work
    public Base someData = new Derived();
};

It won't work in this case, someData will point to an instance of Base when loaded, and only 'string name' will be stored.

ScriptableObject is a quick solution to this problem. If the base class is derived from ScriptableObject like this

[System.Serializable]
class Base: ScriptableObject {
    ...
};

Everything will worked fine until I want to save the GameObject to a prefab. The problem of ScriptableObject is that its actually owned by the Scene instead of the object. So when you create a prefab, the references of the ScriptableObject will lost.

I've searched over the Internet and there were discussions regarding this issue, like

http://www.codingjargames.com/blog/2012/11/30/advanced-unity-serialization/

http://forum.unity3d.com/threads/56947-Saving-instances-of-Scriptable-Objects-to-prefabs

http://feedback.unity3d.com/suggestions/serialization-of-polymorphic-dat?page=1#comments

Some discussions were years ago and there seems still no official solution to this problem. Oneway to get around this is just using MonoBeheviours and hide them in the inspector. Though it works but I don't like it since that's not the purpose of storing data this way.

Another solution seems to be create a custom serializer and just store the data into a json/xml/binary file and then just save the file. However, reference to objects cannot be saved (unless creating something like my own indexing system).

In conclusion, I really hope there will be an offical solution to this, and I'm curious how did PlayMaker storing the information.


blog comments powered by Disqus