← 教程

存档与恢复

本页面为自动翻译,可能包含错误。如果发现问题,请通过“编辑此页面”链接帮助修正。

本教程大约需要二十分钟。您需要先安装 Turian 和 .NET SDK,并且应该先完成入门教程。您将添加一个分数,可以通过一个按键增加、用另一个按键保存,并在下次启动游戏时再次加载。存档系统是 org.mass4.turian.save brick,您可以用与添加其他任何 brick 相同的方式将它添加到项目中。

1. 创建项目

在终端中创建项目并添加存档 brick:

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

新项目不包含存档 brick,因此需要显式添加。游戏会在 Output 面板中报告其进度,因此本教程不需要 UI brick。

2. 编写分数脚本

创建 Assets/ScoreKeeper.cs。保存的数据是一个普通的 record,不引用任何活动节点。组件会在启动时加载分数,每按一次 G 增加十分,并在按下 S 时保存:

namespace Usercode;

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

/// <summary>保存的数据:只包含普通值,不引用活动节点。</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>玩家输入,可选,因此没有它场景也能运行。</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);
    }
}

要点如下。OnUpdate 在游戏线程上运行并读取输入。Load 和 Save 在工作线程上执行文件操作,然后 Async.MainThread 会切回游戏线程,之后才修改组件。busy 防止在第一次操作尚未完成时,第二次按键又启动新的操作。revision 使存档系统能够检测到该槽位是否被他人修改过。

3. 添加组件

在 Scene Tree 中创建一个名为 Score 的空节点。选中它,在 Inspector 中点击 Add Component,然后选择 ScoreKeeper。

4. 保存分数

按 F5。Output 面板会显示 No saved score yet。点击 Game 视图内部,然后按两次 G:Output 会显示 Score is now 20。按 S:Output 会显示 Saved score 20。

再次按 F5 停止。分数保存在游戏中,而不是场景中,因此停止 Play Mode 不会改变您编写的场景。

5. 下次启动时恢复

关闭 Turian Studio,再次打开 SavedScore,然后按 F5。Output 现在会显示 Resumed score 20,并且在您再次按 G 之前,分数已经是 20。

存档会写入您本地的应用数据文件夹中的 turian-saved-score/Saves/account-player-1。FileSaveStorage.ForGame 根据这两个槽位名称选择该位置。每次保存都会先写入一个新文件,然后替换旧文件,因此中断的保存会保留之前的分数。

6. 之后修改格式

每个存档都会记录一个 schema ID 和一个 schema 版本。这里版本从 1 开始。当您修改 ScoreSave 时,需要提高版本号,并告诉存档系统如何升级旧数据。假设版本 2 添加了 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);
    }
}

在 ScoreKeeper 中,将服务改为 new SaveService(storage, "saved-score:score", schemaVersion: 2, migrations: [new AddLevelMigration()]),添加 System.Text.Json 和 System.Text.Json.Nodes 的 using 指令,并在保存时传入一个等级,例如 new ScoreSave(score, 1)。旧存档会在读取时被升级,而磁盘上的文件要等到下次保存时才会被重写。比它更旧的构建无法读取该存档,因为存档系统会拒绝它不认识的 schema 版本。

下一步

编辑此页面