Fabric Yaml Configuration

Fabric Yaml Configuration

用于创建 yaml 配置的模组

基础库

Fabric Yaml 配置库模组

此修改允许你将 yaml 配置文件用作模组的配置。 此修改已内置 snakeyaml 库。

FabricConfiguration 方法

// 设置最终配置的路径
setFile(File file)
setFile(String file)

// 设置原始配置文件的流
// 通常原始配置位于模组资源中。
setDefault(InputStream defaultConfigurationFile)
        
// 初始化配置
intialize()

// 将配置保存到文件
saveConfiguration()
        
// 从文件重新加载配置
// 用于在模组运行期间更新配置。
relaodConfiguration()

简单配置示例

assets/example-mod/config/example-mod.yml

# Тестовая ветка
test:
  integer: 1
  double: 1.1
  string: 'test'
  list:
    - 'test-1'
    - 'test-2'
    - 'test-3'
  section:
    test: 'test'
public class ExampleMod implements ModInitializer {

    public static final Logger LOGGER = LogManager.getLogger();
    public FabricConfiguration configuration = new FabricConfiguration();

    @Override
    public void onInitialize() {
        // 从模组资源中获取默认配置文件
        InputStream defaultConfigurationFile = ExampleMod.class.getResourceAsStream("/assets/example-mod/config/example-mod.yml");
        
        // 将默认配置文件设置到配置中
        configuration.setDefault(defaultConfigurationFile);
        // 设置配置文件路径
        configuration.setFile("config/example-mod.yml");
        // 初始化配置(如果文件存在则加载,否则生成配置)
        try {
            configuration.initialize();
        } catch (IOException e) {
            LOGGER.error("Configuration file cannot be generated", e);
        } catch (InvalidConfigurationException e) {
            LOGGER.error("Configuration file cannot be loaded", e);
        }

}
}

示例代码(将 ItemStack 保存到配置中/从配置中获取)

ItemStack exampleItemStack = new ItemStack(Items.BEDROCK);
NbtCompound itemStackNbt = exampleItemStack.writeNbt(new NbtCompound());
        
configuration.set("item-stack", NbtHelper.toNbtProviderString(itemStackNbt));
        
try {
    configuration.saveConfiguration();
} catch (IOException e) {
    LOGGER.error("Configuration cannot be saved", e);
}

ItemStack itemStack = null;
try {
    itemStack = ItemStack.fromNbt(NbtHelper.fromNbtProviderString(configuration.getString("item-stack")));
} catch (CommandSyntaxException e) {
    LOGGER.error("ItemStack cannot be loaded from configuration", e);
}