Skip to content

Save my own data with the game

Goal: your own state comes back with a load, in the same save as the world.

  1. 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(',')); }
}
  1. 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.

  1. 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).

  • 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 version when the layout of your text changes. Your read gets the version the section was written with, so it can convert an older one.
  • write may return null to leave the section out this time.
  • A save made before the part existed has no section. Pass the absent argument of the LambdaPart constructor to set your defaults then.
  • Register returns false and logs one warning: the key is empty, starts with intrigues., or another part has it.
  • The load restores nothing of yours: the save holds no section under your key, so absent runs 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 PartWriteFailed or PartReadFailed.

More: Your own data in a save, which also covers SaveBehaviour, secret parts and partial saves, and Saving and loading.