Config Files using Abstract Json Config class - SubnauticaModding/Nautilus GitHub Wiki

A common use case for mods is allowing users to customize how it operates via variables that you expose through a configuration file.

SMLHelper allows you to skip most of the reinventing the wheel that often goes hand-in-hand with this very common task, with minimal boilerplate.

Setting Up a Basic Configuration File

Extending ConfigFile

SMLHelper provides the ConfigFile abstract class in the SMLHelper.V2.Json namespace as a base for reading/writing your own configuration files.

Usage is fairly simple:

using SMLHelper.V2.Json;
using UnityEngine;
public class MyConfig : ConfigFile
{
    public int MyInt = -1; // default value
    public bool MyBool = true; // default value
    public KeyCode MyKeyCode = KeyCode.Space; // default value
}

public static class MyMod
{
    public static MyConfig Config { get; } = new MyConfig();

    public static void PatchMethod()
    {
        Config.Load(); // loading from disk, or populating config.json with default values if not found
        Config.MyBool = false; // overriding the default value
        Config.KeyCode = KeyCode.Return; // overriding the default value
        Config.Save();
    }
}

Upon execution of MyMod.PatchMethod(), the above will result in a config.json file being written to your mod's subfolder with the contents:

{
    "MyInt": -1,
    "MyBool": false,
    "MyKeyCode": "Return"
}

Customizing the filename and path

In some cases, you might not want to simply save to config.json. For example, you might be writing a particularly complicated mod and want multiple configuration files. In these cases, you can customize the file path for each ConfigFile as following:

public class StandardConfig : ConfigFile { }

public class CustomConfig : ConfigFile
{
    public CustomConfig() : base("custom") { }
}

public class CustomConfigInSubfolder : ConfigFile
{
    public CustomConfigInSubfolder() : base("custom", "subfolder") { }
}

Given a mod in the folder [gamedir]\QMods\MyMod, in the above example:

  • StandardConfig corresponds to [gamedir]\QMods\MyMod\config.json
  • CustomConfig corresponds to [gamedir]\QMods\MyMod\custom.json
  • CustomConfigInSubfolder corresponds to [gamedir]\QMods\MyMod\subfolder\custom.json

For more details on ConfigFile, check the documentation in Visual Studio.