- Home /
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.
Answer by IgorAherne · Jan 27, 2017 at 12:13 AM
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
Answer by CultureZ · Jan 27, 2017 at 06:25 PM
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.
Saving:
IFormatter binFormatter = new BinaryFormatter();
Stream stream = new FileStream(binFile, FileMode.Create, FileAccess.Write);
binFormatter.Serialize(stream, gameData);
stream.Close();
Loading
IFormatter binFormatter = new BinaryFormatter();
Stream stream = new FileStream(binFile, FileMode.Open, FileAccess.Read, FileShare.Read);
gameData = (GameData)binFormatter.Deserialize(stream);
stream.Close();
2) 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).
http://www.newtonsoft.com/json Saving:
JsonSerializerSettings settings = new JsonSerializerSettings {
PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
string json = JsonConvert.SerializeObject(gameData, Formatting.Indented, settings);
File.WriteAllText(jsonFile, json);
Loading:
string json = File.ReadAllText(jsonFile);
gameData = JsonConvert.DeserializeObject<GameData>(json);
Your answer
Follow this Question
Related Questions
I am getting a serialization exception error when trying to save and load in Unity? 2 Answers
How to deserialize after I've added more members to a class 0 Answers
Serializing / deserializing large lists 0 Answers
Serialized Data Not Saving on Android Build 0 Answers
Issue loading serialized config.dat from persistant Data 0 Answers