Convars
SwiftlyS2's convar system covers creating convars, finding existing ones, replicating values to clients, and querying client-side values.
Access it through Core.ConVar (APIISwiftlyCore.ConVar, type APIIConVarService).
Supported Generic Types
The generic parameter T used by APIIConVar`1, Create<T>, CreateOrFind<T>, and Find<T> supports:
bool, short, ushort, int, uint, long, ulong, float, double, Color, QAngle, Vector, Vector2D, Vector4D, string
The minValue/maxValue overloads are constrained to where T : unmanaged, so a reference type like string only works with the overloads that don't take bounds.
Creating Convars
APIIConVarService.Create has two overloads, both returning the new APIIConVar`1:
Create<T>(name, helpMessage, defaultValue, flags = ConvarFlags.NONE).Create<T>(name, helpMessage, defaultValue, minValue, maxValue, flags = ConvarFlags.NONE), constrained towhere T : unmanaged- both bounds areT?, so passnullfor a bound the convar shouldn't have.
APIIConVarService.CreateOrFind mirrors both overloads, but returns the convar already registered under name if there is one instead of creating a second one.
IConVar<bool> enabled = Core.ConVar.Create("sw_plugin_enabled", "Enable or disable the plugin.", true);
IConVar<int> maxBots = Core.ConVar.Create("sw_plugin_max_bots", "Maximum amount of bots allowed.", 6, 0, 20);
IConVar<float> scale = Core.ConVar.Create("sw_plugin_scale", "Scale factor for the plugin.", 1.0f, 0.5f, null, ConvarFlags.ARCHIVE);
IConVar<bool> feature = Core.ConVar.CreateOrFind("sw_plugin_feature", "Enable feature X.", true);Finding Existing Convars
Typed Find
Looking up an existing engine convar like ConVarsv_cheats:
IConVar<bool>? cheats = Core.ConVar.Find<bool>("sv_cheats");
if (cheats == null)
{
Console.WriteLine("sv_cheats was not found.");
}Find as String
Use APIIConVarService.FindAsString for string-level access, or when the convar's type is unknown.
IConVar? hostname = Core.ConVar.FindAsString("hostname");
if (hostname != null)
{
Console.WriteLine($"hostname = {hostname.ValueAsString}");
}Working with APIIConVar`1
Setting Value queues the change and auto-replicates if the convar is replicated; use APIIConVar`1.SetInternal instead for an immediate, non-replicated change (e.g. inside a hook for that same convar, where the queued set won't apply in time). APIIConVar`1.ReplicateToClient/APIIConVar`1.QueryClient push/pull a single client's value, and TryGetMinValue/TryGetMaxValue/TryGetDefaultValue read the bounds safely.
Every convar also exposes Name and HelpText, a settable Flags, the typed MinValue, MaxValue and DefaultValue, and the HasMinValue/HasMaxValue/HasDefaultValue guards for them - reading or writing MinValue/MaxValue on a convar that has no such bound throws InvalidOperationException, which is what the TryGet* methods avoid.
enabled.Value = false;
enabled.SetInternal(true);
enabled.ReplicateToClient(0, true);
enabled.QueryClient(0, valueAsString => Console.WriteLine($"Client replied with: {valueAsString}"));
Console.WriteLine($"{enabled.Name}: {enabled.HelpText} (flags: {enabled.Flags})");
if (maxBots.TryGetMinValue(out var min)) Console.WriteLine($"Min value: {min}");
if (maxBots.TryGetMaxValue(out var max)) Console.WriteLine($"Max value: {max}");
if (maxBots.TryGetDefaultValue(out var def)) Console.WriteLine($"Default value: {def}");Working with APIIConVar (String API)
Without a generic type, use the non-generic members: ValueAsString, MinValueAsString, MaxValueAsString, DefaultValueAsString (all readable and settable), HasMinValue/HasMaxValue/HasDefaultValue, Flags, SetInternalAsString, ReplicateToClientAsString, QueryClient, and TryGetMinValueAsString/TryGetMaxValueAsString/TryGetDefaultValueAsString - see APIIConVar for the full list. A setter that receives a string it can't parse throws ArgumentException.
APIIConVar`1 derives from APIIConVar, so a typed convar carries the whole string API as well - maxBots.ValueAsString and maxBots.TryGetDefaultValueAsString(...) work on the IConVar<int> created above.
IConVar? anyConvar = Core.ConVar.FindAsString("sv_cheats");
if (anyConvar != null)
{
anyConvar.SetInternalAsString("1");
anyConvar.ReplicateToClientAsString(0, "1");
if (anyConvar.TryGetDefaultValueAsString(out var defaultValue))
Console.WriteLine($"Default value: {defaultValue}");
}Service-Level Replication and Queries
Replicate a value by name to a client, even for convars that don't exist on the server:
Core.ConVar.ReplicateToClient(0, "cl_showfps", "1");
Core.ConVar.ReplicateToAll("cl_teamid_overhead_mode", "2");APIIConVarService.QueryClient is the reverse direction - it asks a client for its value by name and hands the answer to a callback:
Core.ConVar.QueryClient(0, "cl_showfps", clientValue => Console.WriteLine($"Client replied with: {clientValue}"));For client userinfo convars like m_yaw or sensitivity, APIIPlayer.GetClientConvarValue returns the value the server already knows, without a round trip.
ConVar Events
Two events on Core.Event (APIIEventSubscriber) cover convars: OnConVarCreated when a convar is created, and OnConVarValueChanged when its value changes. Both take a single @event parameter, matching EventDelegates.OnConVarCreated and EventDelegates.OnConVarValueChanged, so they can be subscribed to with += or with [EventListener<T>] - see Core Events for the subscription details.
- APIIOnConVarCreated:
ConVarName. - APIIOnConVarValueChanged:
ConVarName,PlayerId(the client that made the change),OldValueandNewValue, both as strings.
public override void Load(bool hotReload)
{
Core.Event.OnConVarCreated += OnConVarCreated;
Core.Event.OnConVarValueChanged += OnConVarValueChanged;
}
private void OnConVarCreated(IOnConVarCreated @event)
{
Console.WriteLine($"ConVar was created: {@event.ConVarName}");
}
private void OnConVarValueChanged(IOnConVarValueChanged @event)
{
if (!@event.ConVarName.StartsWith("sw_"))
return;
Console.WriteLine($"ConVar '{@event.ConVarName}' changed by player #{@event.PlayerId}: '{@event.OldValue}' -> '{@event.NewValue}'");
}Useful for audit logging, debugging, and reacting to config changes without polling Value on a hot path.
The framework tears down every listener a plugin registered on hot reload or
unload automatically - unsubscribe manually (Core.Event.OnConVarCreated -= OnConVarCreated;) only to stop listening earlier.
Reference
APIConvarFlags is a [Flags] enum : ulong mirroring the engine's
FCVAR_* flags, passed to Create/CreateOrFind and readable and writable
through APIIConVar.Flags. The most commonly used ones:
| Flag | Meaning |
|---|---|
NONE | No flags at all - the default for Create/CreateOrFind. |
ARCHIVE | Set to cause it to be saved to vars.rc. |
NOTIFY | Notifies players when changed. |
REPLICATED | Server setting enforced on clients - values are replicated from server to clients. |
CHEAT | Only usable in singleplayer/debug or when sv_cheats is enabled. |
HIDDEN | Doesn't appear in find or auto complete. |
PROTECTED | The value isn't sent to clients - 1 if the value isn't blank/zero, 0 otherwise. |
SPONLY | Cannot be changed by clients connected to a multiplayer server. |
The remaining engine flags (LINKED_COMMAND, DEVELOPMENT_ONLY, GAMEDLL,
CLIENTDLL, USERINFO, REFERENCE, UNLOGGED, INITIAL_SETVALUE,
PER_USER, DEMO, DONTRECORD, PERFORMING_CALLBACKS, RELEASE,
MENUBAR_ITEM, COMMANDLINE_ENFORCED, NOT_CONNECTED,
VCONSOLE_FUZZY_MATCHING, SERVER_CAN_EXECUTE, CLIENT_CAN_EXECUTE,
SERVER_CANNOT_QUERY, VCONSOLE_SET_FOCUS, CLIENTCMD_CAN_EXECUTE,
EXECUTE_PER_TICK, DEFENSIVE) are available on the enum as well - see
APIConvarFlags for the full list.