存档 Schema 让扩展可以将数据保存到存档中,在读档时恢复。典型用途:背包物品、已解锁的图鉴、自定义小游戏进度等。
基本用法
用 defineSave 声明存档字段。每个字段需要三个属性:type(数据类型)、persistence(持久化模式)、default(默认值)。
import { Extension, extension, defineSave } from "@avg-studio/sdk";
@extension({ id: "gallery", label: "鉴赏" })
export class GalleryScreen extends Extension {
static saveSchema = defineSave({
unlockedCGs: {
type: "list",
persistence: "shared",
default: [] as string[],
},
lastPage: {
type: "number",
persistence: "slot",
default: 0,
},
});
}
字段属性
type — 数据类型
| 值 | 说明 |
|---|
"string" | 字符串 |
"number" | 数字 |
"boolean" | 布尔值 |
"list" | 数组 |
type 用于 Studio 调试面板的渲染分类,不参与运行时校验。
persistence — 持久化模式
| 值 | 说明 | 典型用途 |
|---|
"slot" | 跟随存档槽位,不同槽位的数据互相独立 | 背包内容、关卡进度、NPC 好感度 |
"shared" | 跨所有存档共享 | 已解锁的 CG、成就、总游玩时间 |
slot 数据在玩家存档时保存、读档时恢复。shared 数据不属于任何存档槽位,无论读哪个档都始终可用。
default — 默认值
字段的初始值。TypeScript 会从字面量推导出精确类型,this.save.get("lastPage") 自动推断为 number。
数组字段的 default 写 [] as string[],读出来是 readonly string[]——不能 push,只能整体替换 set,避免内部 mutation 不触发落盘。
读写存档数据
通过 this.save 访问存档数据,支持三种方式:
// 命令式读取
const page = this.save.get("lastPage");
// 命令式写入
this.save.set("lastPage", 5);
// React Hook(组件中使用,值变化时自动重渲染)
const [cgs, setCGs] = this.save.useValue("unlockedCGs");
在 React 组件中也可以通过实例方法访问:
// 在方法里
static addToGallery = method({
title: "加入鉴赏",
schema: { scene: { type: "scene", label: "场景" } },
run(ctx, params) {
const current = this.save.get("unlockedCGs");
this.save.set("unlockedCGs", [...current, params.scene]);
},
});
类型安全
defineSave 使用 const 类型参数保留字面量类型。this.save 的所有方法都是强类型的——key 自动补全,value 类型自动推断,拼错的 key 在编译期报错。
未声明 saveSchema 的扩展,this.save 上的任何操作都会编译报错。
存档 Schema 和设置 Schema 的区别:设置是创作者在 Studio 中配置的项目参数(背包格数、槽位数量),存档是游戏运行时产生的玩家数据(背包里的物品、解锁的 CG)。设置在编辑器中修改,存档在游戏中读写。