Storable
按命名空间存取游戏数据、读写并监听跨存档变化的 Storable 方法
Storable 允许你在游戏状态中存储数据。存储在 Storable 中的数据将与当前游戏状态一起保存和加载
如果你需要创建操作数据的动作,可以使用 Persistent 抽象
存储在 Storable 中的数据按命名空间分隔。你可以在不同的命名空间中使用相同的键
例如,你可以在 player1 命名空间中存储玩家 1 的名字,也可以在 player2 命名空间中存储玩家 2 的名字
game 命名空间已经定义且可以存储数据,你可以通过实例化一个新的 Namespace 来添加自己的命名空间
例如,创建一个新的 player1 命名空间,并在其中存储玩家 1 的名字:
type Player1Content = {
name: string;
};
const storable = game.getLiveGame().getStorable();
// 初始化并注册命名空间
const player1namespace = Storable.createNamespace<Player1Content>("player1", {
name: "默认名称",
});
storable.addNamespace(player1namespace);
// 从命名空间中设置数据
const namespace = storable.getNamespace<Player1Content>('player1');
namespace.set('name', 'John Doe');
// 从命名空间中获取数据
const name = namespace.get('name');
console.log(name); // John Doe静态方法
createNamespace<T extends NameSpaceContent<keyof T>>
创建一个新的命名空间
name: string- 命名空间的可读名称initContent: T- 命名空间的初始内容key?: string- 命名空间的键,默认为名称- 返回
Namespace<T>
公共属性
events
EventDispatcher<StorableEvents>- 所有存储事件都经由的分发器:event:storable.change携带 StorableChange,event:storable.restore携带 StorableRestore。优先使用 onChange,它会按命名空间与键过滤。参见监听存储值的变化
公共方法
addNamespace<T extends NameSpaceContent<keyof T>>
namespace: Namespace<T>- 返回
this
getNamespace<T extends NameSpaceContent<keyof T> = any>
key: string- 命名空间的键- 返回
Namespace<T>
setNamespace<T extends NameSpaceContent<keyof T> = any>
key: string- 命名空间的键namespace: Namespace<T>- 返回
this
getNamespaces
- 返回
{ [key: string]: Namespace<any>; }
hasNamespace
key: string- 返回
boolean
removeNamespace
key: string- 返回
this
keys
- 返回
string[]
values
- 返回
Namespace<any>[]
entries
- 返回
[string, Namespace<any>][]
onChange
自 0.19.0 起可用
监听存储值的变化
监听器在新值可读之后才运行,并且只在值确实发生变化时触发——写入一个与当前值相同的值不会报告任何东西;相等性判断是结构性的,因此重建一个内容相同的对象同样不算变化。读档不会报告变化,参见 onRestore
订阅比它所监听的命名空间活得更久:newGame() 与读档都会从头重建每一个命名空间,而注册在这里的监听器能够存活下来。完整说明参见监听存储值的变化
重载 1 / 3
任意已注册命名空间中的任意变化
storable.onChange(({namespace, key, previous, next}) => {
console.log(`${namespace}.${key}: ${previous} -> ${next}`);
});listener: (change: StorableChange) => void- 参见 StorableChange- 返回
EventToken- 调用其cancel()可移除监听器
重载 2 / 3
某一个命名空间中的变化
storable.onChange("persistent:player", ({key, next}) => {...});namespace: string- 命名空间的键,例如new Persistent("player", ...)对应"persistent:player"listener: (change: StorableChange) => void- 返回
EventToken
重载 3 / 3
某一个键的变化
const token = storable.onChange("persistent:player", "gold", ({next}) => {
if (next === 100) achievements.unlock("rich");
});
token.cancel();namespace: string- 命名空间的键key: string- 该命名空间内的键listener: (change: StorableChange) => void- 返回
EventToken
onRestore
自 0.19.0 起可用
监听存储被整体替换——读入存档,或把某个命名空间回退到快照。每次批量应用只触发一次,列出涉及的命名空间,而不是它所隐含的那些变化
此事件触发时,请重新读取你从存储派生出的一切
storable.onRestore(({namespaces}) => {
if (namespaces.includes("persistent:player")) rereadPlayerView();
});listener: (restore: StorableRestore) => void- 参见 StorableRestore- 返回
EventToken- 调用其cancel()可移除监听器
跨读档监听一个值需要同时使用两个信号。onChange 在读档期间是刻意保持沉默的,因此若监听器还需要在读入的存档一开始就处于目标值时触发,就必须在 onRestore 时重新检查该值