维护提醒

BWIKI 全站将于 9 月 3 日(全天)进行维护,期间无法编辑任何页面或发布新的评论。

全站通知:

模组:制作指南/APIs/Config

来自星露谷物语维基
跳到导航 跳到搜索

{{../../header}}

您可以让用户通过标准的config.json文件配置您的模组。SMAPI将自动创建并负责读取、规范化和更新它。

配置模型

创建配置模型

配置模型是一个C#类,其属性代表欲储存的设置。配置模型可以包含从布尔字段到到复杂的对象图在内的几乎任何事物(尽管您应当努力便利玩家)。
这是一个简单的配置模型:

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会自动创建它),您需要:

  1. 创建的配置模型.
  2. 在模组的ModEntry类中读取配置值:
    /// <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会引发异常。

按键绑定设置

可以在模型中使用SMAPI的KeybindList以使用户能够配置按键绑定。它会自动支持多键,以及手柄等的替代按键(例如,支持分屏模式):

class ModConfig
{
   public KeybindList ToggleKey { get; set; } = KeybindList.Parse("LeftShift + F2, LeftTrigger");
}

进行的设置会自动以字符串的形式写入/解析到config.json文件中:

{
   "ToggleKey": "LeftShift + F2, LeftTrigger"
}