How not to handle saving games

I’m a bit wary of serialization in Unity3D. I’m pretty sure everything is gonna break if I just go ahead and serialize everything in one go. I’ve tried using plugins, but they are usually chunky, slow and rarely work. Since I want to release Software Inc. as an early access game, save games need to be backwards compatible, so I decided to roll my own serialization, partly using the BinaryFormatter that comes with Mono/.Net. I’m still not sure whether the save games should be plain-text; if people want to edit save games, they are gonna find a way to do it, anyway.

I wrote a custom dictionary class that returns null if the key is non-existent, so that I can handle missing values from older save games. This can be done with the normal Dictionary<TKey, TValue>, but this makes the code easier on the eyes. Basically you just overwrite the indexer for the class using the syntax:

public TValue this[TKey key] {get; set;}

I then added an abstract class, Writeable, which has methods to serialize and deserialize an object into my dictionary class. It also marks each object it deserializes with a global ID, so that other objects referring to it can find it again. I then use this class to serialize everything that has anything to do with the MonoBehavior class, everything else can be handled by the build-in BinaryFormatter. It’s worth noting that I needed to implement a class to cast to and from Vector3/Quaternion/Color, since these are not serializable by default, luckily they are just a collection of floats.

Finally, I put all my dictionaries in a list and serialize it, while carefully keeping track of the order in which everything is put in the list. Done. Now my code looks like crap, but it works.