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!