Serializing a graph

I am planning to build a simulation game similar to sim city ( but A LOT simpler) .
The problem I have is that the game will probably need a cyclical graph with crossed references, so it is very likely that I .net serialization will not work.

I am wondering if I should use unity’s serialization or another third party library.
I’ve been toying with the idea of using entity framework, but it is probably overkill for a game.

You can use reading from binary file, to literally store bytes in a .txt file.

You can also use ScriptableObjects. Keep in mind that scriptable object instances each get significantly reduced in size, during compilation, by up to x42 times from what we see in Project window.

Remember that Scriptable Objects are the only way to store transform or gameObject references + null values, anything else will lead you to lots and lots of headache

This happens after compilation, after unity recompiled everything into .cpp

I found two ways of doing this:

  1. using binary serialization - It is not backward compatible, so old structures must be preserved with version changes.


IFormatter binFormatter = new BinaryFormatter();
Stream stream = new FileStream(binFile, FileMode.Create, FileAccess.Write);
binFormatter.Serialize(stream, gameData);


IFormatter binFormatter = new BinaryFormatter();
Stream stream = new FileStream(binFile, FileMode.Open, FileAccess.Read, FileShare.Read);
gameData = (GameData)binFormatter.Deserialize(stream);
  1. using a third party library - ah , what a beauty! I was working on a solution until I found this ( that was two days coding my own library thrown to the trash).


JsonSerializerSettings settings = new JsonSerializerSettings {
  PreserveReferencesHandling = PreserveReferencesHandling.Objects
string json = JsonConvert.SerializeObject(gameData, Formatting.Indented, settings);
File.WriteAllText(jsonFile, json);


string json = File.ReadAllText(jsonFile);
gameData = JsonConvert.DeserializeObject<GameData>(json);