Adding a Config File to Your CounterStrikeSharp Plugin
Hard coded values are fine for a test, but a real plugin needs settings: messages, limits, database details. CounterStrikeSharp can create and read a JSON config for you from a plain C# class.
Why use a config
With a config, the owner of the server edits a text file and reloads, instead of waiting for you to change the code and send a new version. It also keeps secrets such as passwords out of the source code.
Describe the settings in a class
Create a class that inherits from BasePluginConfig. Each property is one setting, and the value you assign is the default. JsonPropertyName fixes the name used in the file.
using System.Text.Json.Serialization;
using CounterStrikeSharp.API.Core;
public class MyConfig : BasePluginConfig
{
[JsonPropertyName("WelcomeMessage")]
public string WelcomeMessage { get; set; } = "Welcome to the server!";
[JsonPropertyName("MaxWarnings")]
public int MaxWarnings { get; set; } = 3;
}
Connect it to the plugin
Make the plugin implement IPluginConfig with your config class. CounterStrikeSharp then reads the file and calls OnConfigParsed before Load, handing you the loaded values.
public class MyPlugin : BasePlugin, IPluginConfig<MyConfig>{
public override string ModuleName => "Config Example";
public override string ModuleVersion => "1.0.0";
public MyConfig Config { get; set; } = new();
public void OnConfigParsed(MyConfig config) { Config = config; }}
Where the file is created
The first time the plugin loads, the framework writes the file with your default values to configs/plugins, in a folder named after the plugin. Server owners edit this file.
What the file looks like
The result is a simple JSON file with one entry per property. The owner can change the values and keep the rest.
{
"WelcomeMessage": "Welcome to the server!",
"MaxWarnings": 3
}
Use the values
Read the settings from the Config property anywhere in the plugin, after the config was parsed, for example in Load or in an event handler.
Logger.LogInformation("Warnings allowed: {Max}", Config.MaxWarnings);
Things to remember
Changes to the file are applied when the plugin is loaded again, not instantly. If you rename or remove a property in a new version, tell your users, because their old file still has the old names. And since the config is readable text, do not put anything there you would not want an admin to see.
Was this tutorial useful?
Barlap for the community.