Skip to content

Usage Guide

Owen edited this page Apr 18, 2024 · 7 revisions

1. Creating a serializable config

To begin, we will create a new config class (or edit your existing one) and make it inherit from SyncedConfig.
We must then add the [DataContract] attribute for this to be synced with clients.

[DataContract]
public class ExampleConfig : SyncedConfig<ExampleConfig>

Within this class, we can begin writing out our config entries that we want to sync using SyncedEntry.
We must also mark them with the [DataMember] attribute for the serializer to recognize them.

[DataContract]
public class ExampleConfig : SyncedConfig<ExampleConfig> {
    public ConfigEntry<float> DISPLAY_DEBUG_INFO { get; private set; }

    [DataMember] public SyncedEntry<float> EXAMPLE_VAR { get; private set; }
}

2. Binding config entries

Before binding, we must do a couple of important things.
To begin, make sure your config constructor implements base() with the GUID of your mod.

public ExampleConfig(ConfigFile cfg) : base("MyModName")

Then, add the following line in the constructor.
While you should be able to place it anywhere, if you experience issues, try placing it at the top.

ConfigManager.Register(this);

We can now bind our entries to the BepInEx config file like usual, however we will use the dedicated BindSyncedEntry instead - this is an extension method provided by CSync.

public ExampleConfig(ConfigFile cfg) : base("MyModName") {
    ConfigManager.Register(this);

    EXAMPLE_VAR = cfg.BindSyncedEntry("General", "fExampleVar", 4.1f,
        "An example of a float value that will be synced."
    );
}

3. Specify BepInEx dependency

It is recommended you inform BepInEx that you depend upon CSync.
You can do this by adding a BepInDependency attribute and specifying the GUID of this library.

[BepInPlugin(MyPluginInfo.PLUGIN_GUID, MyPluginInfo.PLUGIN_NAME, MyPluginInfo.PLUGIN_VERSION)]
[BepInDependency("io.github.CSync")]
public class MyPlugin : BaseUnityPlugin

4. Using the config

To use the config class we just made, create a property with the type of config class we created - "ExampleConfig" in this case.
We will then assign this in the Awake method passing in the config provided by BaseUnityPlugin.

At which point, our main class should look something like so:

public class Plugin : BaseUnityPlugin {
    internal static new ManualLogSource Logger { get; private set; }
    public static new ExampleConfig Config { get; private set; }

    Harmony Patcher;

    private void Awake() {
        Logger = base.Logger;
        Config = new(base.Config);

        try {
            Patcher = new(MyPluginInfo.PLUGIN_GUID);
            Patcher.PatchAll();

            Logger.LogInfo("Plugin loaded.");
        } catch(Exception e) {
            Logger.LogError(e);
        }
    }
}

Now we can simply reference Plugin.Config.EXAMPLE_VAR from any class!