20 lines to serialize any type in Unity (Dictionaries, nested lists, etc)

I needed to serialize a Dictionary<int, List> for a MonoBehaviour that also executes in the editor, and I discovered the (well known, as it turns out) limitations of the Unity serializer. I found some solutions on the forums, but they all revolved around a very involved custom Dictionary implementation. I found that it’s much easier, and with a much wider use case than just dictionaries, to serialize your objects manually to a byte array, and have Unity work with that instead. It goes a little something like this:

public class BehaviourWithSpecialSerializationReqs: MonoBehaviour, ISerializationCallbackReceiver
{
  [SerializeField]
  [HideInInspector]
  private byte[] _serializedDictionary;

  private Dictionary<int, List<int>> _dictionaryToSerialize = new Dictionary<int, List<int>>();

  public void OnAfterDeserialize()
  {
    using (MemoryStream stream = new MemoryStream(_serializedDictionary))
    {
        BinaryFormatter formatter = new BinaryFormatter();
        _dictionaryToSerialize = formatter.Deserialize(stream) as Dictionary<int, List<int>>;
    }
  }

  public void OnBeforeSerialize()
  {
    using(MemoryStream stream = new MemoryStream())
    {
      BinaryFormatter formatter = new BinaryFormatter();
      formatter.Serialize(stream, _dictionaryToSerialize);
       _serializedDictionary = stream.ToArray();
    }
  }
}

I hope someone else will find a use for this. Happy serializing!

2 Likes

And if you don’t want to write everything yourself and want to be sure it also works on iOS or other AOT plattforms you may spent some dollars and buy an asset in the asset store which does all this for you. Like Full Inspector 2. It is probably cheaper than the time you would spend to write something similar yourself :wink:

That’s quite useful piece of info. Thanks!

1 Like