模组:制作指南/APIs/Config
阅读
2024-10-15更新
最新编辑:sizau
阅读:
更新日期:2024-10-15
最新编辑:sizau
← 模组:目录
不完整的翻译 本文或部分尚未完全翻译成中文。
欢迎您通过编辑帮助其建设。 |
您可以让用户通过标准的config.json文件配置您的模组。SMAPI将自动创建并负责读取、规范化和更新它。
配置模型
创建配置模型
The config model is a C# class you create, with properties representing the settings you want to store. It can contain almost anything from a few boolean fields to a complex object graph (though you should try to keep things simple for players).
这是一个简单的配置模型:
public sealed class ModConfig
{
public bool ExampleBoolean { get; set; }
public int ExampleNumber { get; set; }
}
这个模型将会保存到config.json中,内容如下:
{
"ExampleBoolean": false,
"ExampleNumber": 0
}
这个属性必须是公开的。
默认值
你可以在数据模型中设置默认值:
public sealed class ModConfig
{
public bool ExampleBoolean { get; set; } = true;
public int ExampleNumber { get; set; } = 5;
}
或使用构造函数来设置默认值:
public sealed class ModConfig
{
public bool ExampleBoolean { get; set; }
public int ExampleNumber { get; set; }
public ModConfig()
{
this.ExampleBoolean = true;
this.ExampleNumber = 5;
}
}
使用配置文件
读取config.json(SMAPI会自动创建它):
- Create your config model.
- Access the config values in your ModEntry class:
/// <summary>The main entry point for the mod.</summary> internal sealed class ModEntry : Mod { /********* ** Properties *********/ /// <summary>The mod configuration from the player.</summary> private ModConfig Config; /********* ** Public methods *********/ /// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides simplified APIs for writing mods.</param> public override void Entry(IModHelper helper) { this.Config = this.Helper.ReadConfig<ModConfig>(); bool exampleBool = this.Config.ExampleBoolean; } }
就是这样!当玩家启动游戏时,如果config.json文件尚不存在,SMAPI就会使用您在模型中提供的默认配置选项自动创建该它。如果您需要保存部分更改,就可以使用this.Helper.WriteConfig(this.Config)来进行。
请注意,如果用户没有提供有效的JSON,那么ReadConfig会引发异常。
按键绑定设置
- 主要文章:模组:制作指南/APIs/Input
You can use SMAPI's KeybindList in your model to let users configure keybinds. This automatically supports multi-key or alternative bindings (e.g., to support split-screen mode):
class ModConfig
{
public KeybindList ToggleKey { get; set; } = KeybindList.Parse("LeftShift + F2, LeftTrigger");
}
进行的设置会自动以字符串的形式写入/解析到config.json文件中:
{
"ToggleKey": "LeftShift + F2, LeftTrigger"
}