Implementing The Odin Serializer


While Odin by default injects itself into the inspector for every type that doesn't already have a custom editor defined, the serialization system is more conservative than that. You always have to explicitly decide to make use of Odin's serialization system.

Using it is very simple, though: you merely have to inherit from one of our special Serialized classes, such as SerializedMonoBehaviour or SerializedScriptableObject; all commonly inherited Unity types are supported in this way.

public class YourMonoBehaviour : SerializedMonoBehaviour
{
    [SerializeField]
    private object SerializedPrivateField;

    public object SerializedField;

    [OdinSerialize]
    public object SerializedProperty { get; set; }
}

If this doesn't work for you, for example because you already have a specific base type you need to inherit from, it is very easy to implement the serialization yourself where you need it, by implementing Unity's ISerializationCallbackReceiver interface, and using Odin's UnitySerializationUtility class.

This is the complete code for a custom Odin-serialized MonoBehaviour:

[ShowOdinSerializedPropertiesInInspector]
public class CustomSerializedMonoBehaviour : MonoBehaviour, ISerializationCallbackReceiver, ISupportsPrefabSerialization
{
    [SerializeField, HideInInspector]
    private SerializationData serializationData;

    SerializationData ISupportsPrefabSerialization.SerializationData { get { return this.serializationData; } set { this.serializationData = value; } }

    void ISerializationCallbackReceiver.OnAfterDeserialize()
    {
		UnitySerializationUtility.DeserializeUnityObject(this, ref this.serializationData);
    }

    void ISerializationCallbackReceiver.OnBeforeSerialize()
    {
		UnitySerializationUtility.SerializeUnityObject(this, ref this.serializationData);
    }
}

This is the complete code for a custom Odin-serialized ScriptableObject:

[ShowOdinSerializedPropertiesInInspector]
public class CustomSerializedScriptableObject : ScriptableObject, ISerializationCallbackReceiver
{
    [SerializeField, HideInInspector]
    private SerializationData serializationData;

    void ISerializationCallbackReceiver.OnAfterDeserialize()
    {
		UnitySerializationUtility.DeserializeUnityObject(this, ref this.serializationData);
    }

    void ISerializationCallbackReceiver.OnBeforeSerialize()
    {
		UnitySerializationUtility.SerializeUnityObject(this, ref this.serializationData);
    }
}

This website is brand new and built with the Odin 2.1 beta in mind. This means you might discover some features such as attribute expressions that are only available in the beta.

You can download the 2.1 beta from here and read the patch-notes here.