Save my own data with the game
Goal: your own state comes back with a load, in the same save as the world.
The recipe
Section titled “The recipe”- Keep your state in a class with two methods: one returns it as text, one takes the text back. Example, copied from
SaveSamples.cs. Compiled against the package’s runtime assembly; not run in Unity.
public sealed class Inventory{ public List<string> Items = new List<string>(); public string Write() => string.Join(",", Items); public void Read(string text) { Items.Clear(); if (!string.IsNullOrEmpty(text)) Items.AddRange(text.Split(',')); }}- Register a part for it. Example, copied from the same file. Compiled against the package’s runtime assembly; not run in Unity.
IntrigueSave.Register(new LambdaPart("game.inventory", 1, () => inventory.Write(), (text, version) => inventory.Read(text)));The namespace is MrW.Intrigues.SaveSystem. The four arguments are a key, a version, the function that writes and the action that reads. The shorter form IntrigueSave.Register(key, version, write, read) makes the same part and returns it, or null when it is refused.
- Save and load as you do already. Every save now holds a section named
game.inventory, and every load reads it back.
You will see: after a load, inventory.Items holds what it held when you saved. The part is read after the actors have loaded (SavePhase.AfterActors).
Things to know
Section titled “Things to know”- The registration stays across new games, loads and scene changes until you call
IntrigueSave.Unregister. Register once, not on every scene. - Keep the key stable and give it your own prefix. Keys that start with
intrigues.belong to the package. - Raise
versionwhen the layout of your text changes. Yourreadgets the version the section was written with, so it can convert an older one. writemay returnnullto leave the section out this time.- A save made before the part existed has no section. Pass the
absentargument of theLambdaPartconstructor to set your defaults then.
What can go wrong
Section titled “What can go wrong”Registerreturnsfalseand logs one warning: the key is empty, starts withintrigues., or another part has it.- The load restores nothing of yours: the save holds no section under your key, so
absentruns instead. A part registered after its phase was read in a running load gets its section once, right away. - Your part throws: the save or the load goes on without it, and the problem is reported as
PartWriteFailedorPartReadFailed.
More: Your own data in a save, which also covers SaveBehaviour, secret parts and partial saves, and Saving and loading.