搬运自OpenMod官网,经过翻译,可能有些不足,欢迎指正!原文链接
存储
IDataStore服务提供了一种保存和加载持久数据的方法。
默认数据存储使用yaml文件进行序列化。
读写数据
假设要保存并加载以下类:
[Serializable] public class PlayersData { public List<string> OwnerNames { get; set; } }
——————————————————————————————
public class MyPlugin : OpenModUniversalPlugin { // Defines the key for the data. The default data store uses the key as the file name for the yaml file. // In this case, the file will be named owners.data.yaml public const string OwnersKey = "owners"; private readonly IDataStore m_DataStore; public MyPlugin(IDataStore dataStore, IServiceProvider serviceProvider) : base(serviceProvider) { m_DataStore = dataStore; } public async Task OnLoadAsync() { // first check if the data exists and create it if it does not exist if(!await m_DataStore.ExistsAsync(OwnersKey)) { await SeedData(); } var data = await m_DataStore.LoadAsync<PlayersData>(OwnersKey); // do something with data await m_DataStore.SaveAsync<PlayersData>(OwnersKey, data); } private async Task SeedData() { // create default data await m_DataStore.SaveAsync(OwnersKey, new PlayersData { OwnerNames = new List<string> { "Trojaner" } }); } }
更改观察者
当密钥的数据发生更改时(例如,如果用户手动编辑了文件),可以使用更改观察程序自动重新加载数据:
var fileChangeWatcher = m_DataStore.AddChangeWatcher(OwnersKey, this, OnOwnersChanged); public void OnOwnersChanged() { // 做一些事情,例如再次使用LoadAsync读取数据。 }
你可以用fileChangeWatcher.Dispose()停止监听。
命名IDataStore.SaveAsync不会触发更改观察者。