Enum Serialization in Unity

Unity, along with other engines, tend to serialize enum variables as an int.  It makes sense, enums in code are int values, you can add, subtract and even do bit-wise operations on them.  However most of the time this isn't what you want as I talk about in this post.

So how do we trick Unity into serializing enums as strings? Through the use of PropertyDrawer.  With it we create a unique editor drawing for our enum-like variables.  I'll attach all of the exmaple code bellow, including how to handle enums used as masks.

First we create our SerializableEnum class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
[Serializable]
public class SerializableEnum<T> where T : struct, IConvertible
{
    public T Value
    {
        get { return m_EnumValue; }
        set { m_EnumValue = value; }
    }

    [SerializeField]
    private string m_EnumValueAsString;
    [SerializeField]
    private T m_EnumValue;
}

We can't force a Templated class to accept an Enum only...but we can get as close as possible.

In order to use the class and the special serialization here is what it looks like in your class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class NewBehaviourScript : MonoBehaviour {

    public enum ExampleEnum
    {
        EE_One,
        EE_Two,
        EE_Three,
        EE_Four
    }
    [Serializable]
    public class ExampleEnumClass : SerializableEnum<ExampleEnum> { }

    public ExampleEnumClass m_EnumVariable;
}

Unfortunately there are a lot of extra things we have to do here, we need to create our own non-templated class to use because Property drawers do not support templated classes.  This also requires referring to the Enum value as m_EnumVariable.Value but in exchange, serialization is done by string automatically and you don't have the issue of trying to insert an enum value without messing up all of your Unity game objects.

Check out these files for the details: