← Tutorials

Save and resume

This tutorial takes about twenty minutes. You need Turian and the .NET SDK installed, and you should have finished the getting-started tutorial first. You will add a score that you can increase with a key, save with another key, and load again the next time the game starts. The save system is the org.mass4.turian.save brick, which you add to the project the same way as any other brick.

1. Create the project

From a terminal, create a project and add the save brick:

turian-cli new SavedScore
turian-cli brick add org.mass4.turian.save --project SavedScore
turian-studio --project SavedScore

A new project does not include the save brick, so you add it explicitly. The game reports its progress in the Output panel, so you do not need the UI brick for this tutorial.

2. Write the score script

Create Assets/ScoreKeeper.cs. The saved data is a plain record with no references to live nodes. The component loads the score when it starts, adds ten points for each G, and saves when you press S:

namespace Usercode;

using System.Text.Json.Serialization;
using System.Threading;
using Turian.Engine.Save;

/// <summary>The saved data: plain values only, no references to live nodes.</summary>
public sealed record ScoreSave(int Score);

public class ScoreKeeper : Component
{
    readonly SaveSlot slot = new("score");
    SaveService saves = null!;
    string? revision;
    bool busy = true;
    int score;

    /// <summary>The player input, optional so the scene also runs without it.</summary>
    [InjectService(Optional = true), JsonIgnore]
    public IInputSource? Input { get; private set; }

    /// <inheritdoc />
    public override void OnStart()
    {
        var storage = FileSaveStorage.ForGame(new SaveSlot("saved-score"), new SaveSlot("player-1"));
        saves = new SaveService(storage, "saved-score:score", schemaVersion: 1);
        Async.Run(Load);
    }

    /// <inheritdoc />
    public override void OnUpdate(float deltaTime)
    {
        if (Input is null || busy)
        {
            return;
        }

        if (Input.WasKeyPressed(Key.G))
        {
            score += 10;
            Log.Logger.LogInformation("Score is now {Score}", score);
        }

        if (Input.WasKeyPressed(Key.S))
        {
            busy = true;
            var snapshot = new ScoreSave(score);
            var expected = revision;
            Async.Run(token => Save(snapshot, expected, token));
        }
    }

    async ValueTask Load(CancellationToken token)
    {
        var loaded = await saves.LoadAsync<ScoreSave>(slot, cancellationToken: token).ConfigureAwait(false);
        await Async.MainThread(token);
        revision = loaded?.Revision;
        score = loaded?.State.Score ?? 0;
        busy = false;
        if (loaded is null)
        {
            Log.Logger.LogInformation("No saved score yet");
        }
        else
        {
            Log.Logger.LogInformation("Resumed score {Score}", score);
        }
    }

    async ValueTask Save(ScoreSave snapshot, string? expected, CancellationToken token)
    {
        var written = await saves.SaveAsync(slot, snapshot, new SaveMetadata { GameVersion = "0.1.0" }, expected, token)
            .ConfigureAwait(false);
        await Async.MainThread(token);
        revision = written;
        busy = false;
        Log.Logger.LogInformation("Saved score {Score}", snapshot.Score);
    }
}

The key points are these. OnUpdate runs on the game thread and reads the input. Load and Save do their file work on a worker, then Async.MainThread returns to the game thread before they change the component. busy stops a second key press from starting work while the first is still running. The revision is what lets the save system detect that someone else changed the slot.

3. Attach it

Create an empty node named Score in the Scene Tree. Select it, click Add Component in the Inspector and choose ScoreKeeper.

4. Save a score

Press F5. The Output panel reports No saved score yet. Click inside the Game view, then press G twice: the Output shows Score is now 20. Press S: the Output shows Saved score 20.

Press F5 again to stop. The score lives in the game, not in the scene, so stopping Play Mode does not change your authored scene.

5. Resume on the next launch

Close Turian Studio, open SavedScore again and press F5. The Output now shows Resumed score 20, and the score is 20 before you press G again.

The save is written to your local application data folder, under turian-saved-score/Saves/account-player-1. FileSaveStorage.ForGame chooses that location from the two slot names. Each save writes to a new file first and then replaces the old one, so an interrupted save leaves the previous score in place.

6. Change the format later

Every save records a schema ID and a schema version. The version starts at 1 here. When you change ScoreSave, you increase the version and tell the save system how to upgrade the old data. Suppose version 2 adds a Level:

public sealed record ScoreSave(int Score, int Level);

sealed class AddLevelMigration : ISaveMigration
{
    public int FromVersion => 1;

    public string SerializerId => "json";

    public byte[] Upgrade(ReadOnlyMemory<byte> data)
    {
        var state = JsonNode.Parse(data.Span)!.AsObject();
        state["Level"] = 1;
        return JsonSerializer.SerializeToUtf8Bytes(state);
    }
}

In ScoreKeeper, change the service to new SaveService(storage, "saved-score:score", schemaVersion: 2, migrations: [new AddLevelMigration()]), add the System.Text.Json and System.Text.Json.Nodes usings, and pass a level in the save, for example new ScoreSave(score, 1). Old saves are upgraded when they are read, and the file on disk is not rewritten until the next save. A build that is older than the save cannot read it, because the save system rejects a schema version it does not know.

Next steps

Edit this page