Search code examples
c#unity-game-engineserializationdeserializationscriptable-object

Serialize Script Instance in a ScriptableObject in Unity


I know this can be done because the amazing plugin Odin, has some epic serialization tools.

I was hoping I could do this using Odin but even their [Serialize] tag doesn't work.

I want to serialize a new instance of a script inside of a Scriptable Object.

With Odin, you can serialize dictionaries, and if you serialize a dictionary which holds instance of an interface (script) it allows you to create a new instance of that script inside the dictionary like so:

enter image description here

Since its possible to store an instance of a script inside of a dictionary I am curious how this can be done on its own.

The script I want to save is a generic script with only functions and an empty constructor.

Do you know a why to serialize the instance of an interface (script) inside of a ScriptableObject?

Ideally I could create an attribute some how and just force it to serialize like so:

public class MyClass: MonoBehaviour
{
    [ForceSerialize]
    public IScript scriptToSerialize;

}

And then in the inspector I could just click the box and create a new instance of that script to be attached to the object.


Solution

  • You don't need any [Serialize] tag, MyClass simply has to inherit from Sirenix.OdinInspector.SerializedMonoBehaviour instead of MonoBehaviour. These "Serialized" class (also exists for ScriptableObjects and the likes) need to be used in order for Odin's custom serialization to work, which would make your field appear in the inspector.

    This script works for me:

    using Sirenix.OdinInspector;
    
    public class MyScript : SerializedMonoBehaviour
    {
        public IScript scriptToSerialize;
    }
    
    public interface IScript { }