While you can implement your own configuration system for your plugin, it is highly recommended to use the built-in configuration system provided by SE Launcher. This system offers centralized storage, a unified format, and seamless integration with the plugin lifecycle.
The launcher provides a utility class called ConfigHandler
, which can be used to register and manage your plugin's configuration files.
You can retrieve an instance of ConfigHandler
via the game service provider:
var handler = MySandboxGame.Services.GetRequiredService<ConfigHandler>();
Here’s a simple example of a configuration class with one setting:
public class Config
{
public string UserName { get; set; } = "John";
}
The class must be public, have a parameterless constructor, and its properties must be publicly gettable and settable to be properly handled by the configuration system.
using CringePlugins.Config;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using Sandbox;
using VRage.Plugins;
namespace TestPlugin;
public class Plugin : IPlugin
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
public void Dispose()
{
}
public void Init(object gameInstance)
{
Log.Info("Test Plugin init");
var handler = MySandboxGame.Services.GetRequiredService<ConfigHandler>();
using var config = handler.RegisterConfig<Config>("test");
Log.Info("Hello, {UserName}", config.Value.UserName);
}
public void Update()
{
}
}
RegisterConfig<T>(string id)
registers a config and returns a ConfigReference<T>
..Value
contains the current config instance.If your config class is mutable (as in the example), changing a property like this:
config.Value.UserName = "NewName";
will not automatically persist the changes.
To update and save the configuration, you need to assign a new instance to the .Value
property:
config.Value = new Config
{
UserName = "NewName"
};
This ensures that the new value is persisted to disk and broadcast to other consumers of the same config.
The ConfigReference<T>
returned by RegisterConfig
must be disposed when no longer needed. This releases associated resources and unhooks change tracking.
In the example above, the config is used only during Init()
and disposed immediately with a using
block.
If you need to access the config during the whole plugin lifetime, store the reference in a field, and dispose of it inside the Dispose()
method:
private ConfigReference<Config>? _config;
public void Init(object gameInstance)
{
var handler = MySandboxGame.Services.GetRequiredService<ConfigHandler>();
_config = handler.RegisterConfig<Config>("test");
Log.Info("Welcome, {UserName}", _config.Value.UserName);
}
public void Dispose()
{
_config?.Dispose();
}
This approach ensures that your plugin holds the configuration safely throughout its lifecycle and disposes of it properly when the game or plugin is closed.