Skip to content

Tutorial 11: Save, load and your own data

A tiny save menu with three buttons, and an inventory that is written into the same save as the world.

  1. Save writes the running game to the slot slot1.
  2. Load restores that slot and tells you what came back.
  3. List names the slots, and says which cannot be loaded.

You need a scene that already runs Intrigues, with the Intrigue Manager and its Save System component. A canvas with a TextMeshPro label and three buttons is enough for the menu. The background pages are Saving and loading and Your own data in a save.

Create SaveMenu.cs. Every call here returns a result object and never throws, so the script tests Ok and reads Reason.

Example. Compiled against the package’s runtime assembly; not run in Unity.

using MrW.Intrigues.SaveSystem;
using TMPro;
using UnityEngine;
namespace MyGame
{
public class SaveMenu : MonoBehaviour
{
[SerializeField] private TMP_Text note;
[SerializeField] private string slotId = "slot1";
public async void SaveToSlot()
{
var saved = await IntrigueSaveSystem.Instance.SaveAsync(slotId, new SaveRequest { Title = "My save" });
Say(saved.Ok ? "Saved." : "Save failed: " + saved.Reason);
}
public async void LoadFromSlot()
{
var loaded = await IntrigueSaveSystem.Instance.LoadAsync(slotId, new LoadRequest { Scene = SceneMode.Current });
if (!loaded.Ok)
{
Say("Load failed: " + loaded.Status + ": " + loaded.Reason);
return;
}
var report = loaded.Report;
Say($"Loaded {report.Actors} actors, {report.Runs} running schemes."
+ (report.HasDataLoss ? " Something did not come back." : ""));
if (report.HasDataLoss)
foreach (var problem in loaded.Problems)
Debug.Log(problem.ToString());
}
public async void ListSlots()
{
var list = await IntrigueSaveSystem.Instance.ListAsync();
if (!list.Ok) { Say("List failed: " + list.Reason); return; }
var lines = new System.Text.StringBuilder();
foreach (var slot in list.Slots)
lines.AppendLine(slot.Id + (slot.CanLoad ? "" : " (cannot load: " + slot.Reason + ")"));
Say(lines.Length == 0 ? "No saves." : lines.ToString());
}
private void Say(string text)
{
if (note != null) note.text = text;
Debug.Log(text);
}
}
}

Put the script on an object of the canvas. Drag the label into Note. On each button add an On Click entry that calls SaveToSlot, LoadFromSlot or ListSlots of the menu.

Three things to know:

  • The calls run on the main thread, so call them from a button or a key, not from another thread.
  • SceneMode.Current restores the game in place, in the scene that holds the actors now. A load from a main menu usually wants SceneMode.FromSave, which loads the scene named in the save. A LoadRequest you create yourself starts at Current, so say which one you mean.
  • The slot name slot1 is valid: letters, digits, space, -, _ and . are allowed. See Your own storage for the full rule.

Your game has state that Intrigues does not know about, such as what the player carries. A save part writes it into the same file under its own key, and a load reads it back. Create Inventory.cs. It is copied from the package’s Save System sample, SaveSamples.cs.

Example. Compiled against the package’s runtime assembly; not run in Unity.

using System.Collections.Generic;
namespace MyGame
{
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(','));
}
}
}

Write returns the state as text and Read takes it back. An item name with a comma in it would break this format, so keep commas out of the names or choose another separator.

Now register a part for it. Create InventoryKeeper.cs, and put it on an object that stays on while you play.

Example. Compiled against the package’s runtime assembly; not run in Unity.

using MrW.Intrigues.SaveSystem;
using UnityEngine;
namespace MyGame
{
public class InventoryKeeper : MonoBehaviour
{
public static readonly Inventory Inventory = new Inventory();
private LambdaPart part;
private void OnEnable()
{
// Key, version, what writes, what reads, and what runs when a save has no such section.
var made = new LambdaPart("game.inventory", 1, () => Inventory.Write(), (text, version) => Inventory.Read(text),
absent: () => Inventory.Items.Clear());
if (IntrigueSave.Register(made)) part = made;
else Debug.LogWarning("The part game.inventory was refused.");
}
private void OnDisable()
{
if (part != null) IntrigueSave.Unregister(part);
part = null;
}
[ContextMenu("Add a torch")]
private void AddTorch() => Inventory.Items.Add("torch");
[ContextMenu("Log the inventory")]
private void LogItems() => Debug.Log("Inventory: " + (Inventory.Items.Count == 0 ? "empty" : Inventory.Write()));
}
}

The first four arguments are the key, the version, what writes and what reads. The fifth, absent, runs when a loaded save has no section under your key, for example a save made before the part existed. IntrigueSave.Register(part) gives true or false, so keep the LambdaPart to unregister it. Keep the key stable and give it your own prefix: keys that start with intrigues. belong to the package and are refused. Raise the version when your text changes layout. Your read then receives the version the section was written with.

A registration stays across new games, loads and scene changes until you unregister. That is why this script unregisters in OnDisable. The sample registers once from a static method instead; use that when your inventory is not tied to a scene object.

Press Play and look at the object with Inventory Keeper. Use the three dots of the component header.

  1. Choose Add a torch twice, then Log the inventory. The Console says Inventory: torch,torch.
  2. Press Save. The label says Saved. and the Console repeats it.
  3. Choose Add a torch again and log. Three torches.
  4. Press Load. The label says Loaded with the number of actors and running schemes in the save. Log again: two torches. The part is read after the actors have loaded.
  5. Press List. The label names slot1.

By default the file is in the folder Intrigues Saves, inside Unity’s persistent data folder, with the extension .isav. You can change both on the Save System component.

The inventory here is a static field. With domain reload switched off in the editor, it carries over from one Play session to the next, so clear it yourself when you start a test.

loaded.Report says what the save held and what did not come back.

Member Meaning
Actors, Runs, Visits How many actors, running schemes and running nodes the save holds.
HasDataLoss True when a problem of severity DataLoss or Error was found.
Problems Every problem, in the order found.

loaded.Ok is true even when there are problems, so test HasDataLoss too. Test a problem by its code, never by its message. The statuses and codes are on Save and load results.

What you see Why What to do
Register gives null and one warning. The key is empty, starts with intrigues., or another part has it. Pick your own key.
After a load the inventory still holds what it had before. The save has no section under your key (it was made before the part existed), and nothing resets the inventory. Give the part an absent action, as in the script above.
The save fails with a reason. A slot name is not valid, or the call came off the main thread. Read Status and Reason.
The call is refused with RefusedOffHost in a multiplayer game. Only the host saves and loads. Offer the buttons on the host.