Skip to content

快速开始

本指南将从零开始带你在模组中集成 Tritium Configuration,并完成本地化与界面接入。

1. 添加依赖

确保项目已经包含 Cloth Config v15 与本库(Fabric/NeoForge 多端均可)。

可查看依赖集成以了解如何添加依赖。

2. 定义配置类

使用注解描述结构、分组与约束(可使用 static 字段或实例字段,推荐初学者使用 static):

java
package your.mod;

import me.zcraft.tc.annotation.*;

@ConfigVersion(1)
public class MyConfig {
  @SubCategory("通用")
  public static General general = new General();

  @ClientOnly
  @SubCategory("客户端")
  public static Client client = new Client();

  public static class General {
    public boolean enabled = true;

    @Range(min = 1, max = 256)
    public int maxEntities = 64;

    public Mode mode = Mode.SIMPLE;
    public enum Mode { SIMPLE, VANILLA }
  }

  @ClientOnly
  public static class Client {
    public java.util.List<String> whitelist = java.util.Arrays.asList(
      "minecraft:player", "minecraft:villager"
    );
  }

  // 可选:整体校验
  public void validateConfig() {
    if (!general.enabled && general.maxEntities > 0) {
      throw new IllegalArgumentException("当禁用时,maxEntities 必须为 0");
    }
  }
}

3. 注册并初始化

在模组初始化早期注册配置(并可选择自定义文件名):

java
import me.zcraft.tc.config.TritiumConfig;

public class YourModInit {
  public static final String MOD_ID = "your_mod";

  public static final TritiumConfig CONFIG = TritiumConfig
    .register(MOD_ID, MyConfig.class)
    .filename("my_config"); // 可选:默认为 your_mod_config

  public static void onInitialize() {
    // 其他初始化逻辑
  }
}

注册后会:

  • 生成默认配置文件(若不存在)
  • 进行一次校验
  • 启动文件监视器(热重载)

4. 在代码中读取值

  • 使用 static 字段时:直接引用即可。
  • 使用实例字段时:通过 TritiumConfig.getConfig(MOD_ID).get() 获取配置实例。
java
boolean enabled = MyConfig.general.enabled;
int max = MyConfig.general.maxEntities;
java.util.List<String> whitelist = MyConfig.client.whitelist;

5. 打开配置界面(可选)

自动生成的 UI 基于 Cloth Config v15:

java
import me.zcraft.tc.config.TritiumAutoConfig;
import net.minecraft.client.gui.screens.Screen;

Screen screen = new TritiumAutoConfig(CONFIG).createConfigScreen(parent);

UI 的标题、分类、每个条目的名称与提示文本都可本地化(见“国际化”章节)。

6. 配置文件位置与热重载

  • 默认路径:config/<modId>/<filename>.toml
  • 修改后 2 秒内会自动检测并执行 reload(),无需重启游戏

7. 构建与发布建议

  • 提供完善的本地化键与 tooltip,提高可用性
  • 规划好分组层级(避免过深)
  • 首个版本建议将 @ConfigVersion 设为 1,后续结构变化再升级版本并提供迁移