S&box Wiki

Revision Difference

ConVars#551157

<cat>Code.Input</cat>⤶ <title>ConVars</title> Console Variables (convar) are a great way to tweak and control game features or debugging tools dynamically during runtime. They can be defined and accessed through different types depending on where they are used. # Types - [Client](https://asset.party/api/Sandbox.ConVar.ClientAttribute): Console variable that is available on the client - [ClientData](https://asset.party/api/Sandbox.ConVar.ClientDataAttribute): A property with this attribute will be made a ClientData ConVar. It will be able to be changed by the client at any time and changes will be sent to the server. The variables will be accessible on the server by name on the Client object. - [Engine](https://asset.party/api/Sandbox.ConVar.EngineAttribute): Console variable that is available everywhere, always - [Menu](https://asset.party/api/Sandbox.ConVar.MenuAttribute): Console variable that is available via the menu - [Replicated](https://asset.party/api/Sandbox.ConVar.ReplicatedAttribute): Properties with this attribute will be replicated from the server to each client. The value can only be changed by the server or the server admin, but clients can read the value at any time. - [Server](https://asset.party/api/Sandbox.ConVar.ServerAttribute): Console variable that is available on the server # Defining Convars must be static. ``` [ConVar.Client( "my_convar_name" )] public static float MyConVar { get; set; } ``` ## ClientData ClientData doesn't need to be static - you can also (optionally) store ClientData convars as a member on an Entity. ``` [ConVar.ClientData( "tool_current" )] public string UserToolCurrent { get; set; } = "boxgun" ``` # Accessing ``` // You can access it directly - but only within the same realm currentTool = UserToolCurrent; // Or via the console system currentTool = ConsoleSystem.GetValue( "tool_current" ); ``` ## ClientData To access static ClientData convars on the server, you need to go through a Client object. ``` public override void Simulate( Client owner ) { currentTool = owner.GetClientData( "my_convar" ); } ``` If your ClientData convar is a member of an entity, it can be accessed directly. ``` // Will always access the convar value on the client, but on the server will access // it via the entity's GetClientOwner(). If the entity has no client owner, will be null. currentTool = UserToolCurrent; ```