### Install Dependencies Source: https://github.com/carboncommunity/carbon.documentation/blob/main/README.md Run this command to install all project dependencies. Ensure you have Node.js and npm installed. ```bash setup.bat ``` -------------------------------- ### Full Example Plugin Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/localization.md A complete example plugin demonstrating localization, command registration, permission checks, and dynamic message formatting. ```cs using System.Collections.Generic; namespace Oxide.Plugins; [Info("HelloThere", "Bubbafett", "1.0.1")] [Description("Cool plugin that tells players about cool permissions.")] public class HelloThere : RustPlugin { public const string PermUse = "HelloThere.use"; protected override void LoadDefaultMessages() { lang.RegisterMessages(new Dictionary { ["Hello"] = "Hello there!", ["NoPerm"] = "You do not have permission to use this command.", ["Welcome"] = "Welcome to the server, {0}!", }, this, "en"); } private void Init() { ``` -------------------------------- ### Configuration File Example Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/vault.md Example of a configuration file showing how sensitive data is referenced using the `{factory:id}` format. ```json { "Username": null, "Password": "{global:pwd}" } ``` -------------------------------- ### Full Bridge Example in C# Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/bridge.md This example demonstrates starting a Bridge server, connecting a client, and sending various message types including RPC, commands, and custom messages. It also shows how to handle incoming messages within a custom BridgeMessages class. Ensure the Bridge server and client are configured with matching ports and passwords. ```csharp using Carbon.Components; using Facepunch; namespace Carbon.Plugins; [Info("BridgeExample", "Carbon Community", "1.0")] public class BridgeExample : CarbonPlugin { public BridgeClient client; private async void OnServerInitialized() { var messages = new CustomBridgeMessages(); Bridge.Server?.Shutdown(); // Start a Bridge server on this Rust process Bridge.Server ??= new(); Bridge.Server.Start(RCon.Port + 1, "supersecretpass", null, messages); // Connect to that same Bridge server, can adjust it to connect to another local or external server, make sure ports are open client = await Bridge.StartClient("localhost", RCon.Port + 1, "supersecretpass", messages); var rpc = BridgeWrite.Rent(); rpc.BridgeMessage(BridgeMessages.Channels.Rpc); rpc.Int32(123); rpc.String("Manuela"); rpc.Float(43.7f); await client.Send(rpc); BridgeWrite.Return(ref rpc); var command = BridgeWrite.Rent(); command.BridgeMessage(BridgeMessages.Channels.Command); command.String("env.time"); command.Int32(1); command.String("12.5"); await client.Send(command); BridgeWrite.Return(ref command); var custom = BridgeWrite.Rent(); custom.BridgeMessage(BridgeMessages.Channels.Custom); custom.String("Hello world!"); await client.Send(custom); BridgeWrite.Return(ref custom); foreach (var connection in Bridge.Server.Connections.Values) { var rpc2 = BridgeWrite.Rent(); rpc2.BridgeMessage(BridgeMessages.Channels.Rpc); rpc2.Int32(865); rpc2.Int32(5); rpc2.Int32(10); connection.Send(rpc2); BridgeWrite.Return(ref rpc2); } } private async void Unload() { if (client != null) { await client.Disconnect(); client = null; } } public class CustomBridgeMessages : BridgeMessages { /// /// You can handle your own custom identified packets here, just like how Rust RPCs work. /// /// protected override void OnRpc(BridgeRead read) { var rpcId = read.Int32(); switch (rpcId) { case 123: { var val1 = read.String(); var val2 = read.Float(); Logger.Log( $"Mrs {val1} has {val2}% chance of survival! [{(read.Connection == null ? "Server" : "Client")}]"); break; } case 865: { var val1 = read.Int32(); var val2 = read.Int32(); Logger.Log($"{val1} + {val2} = {val1 + val2} [{(read.Connection == null ? "Server" : "Client")}]"); break; } } } /// /// Can fire server server/unrestricted commands if you want. /// /// protected override void OnCommand(BridgeRead read) { using var args = Pool.Get>(); var command = read.String(); var argCount = read.Int32(); for (var i = 0; i < argCount; i++) { args.Add(read.String()); } ConsoleSystem.Run(ConsoleSystem.Option.Server, command, args.ToArray()); } /// /// Go wild doing whatever you need to be doing. Imma just print this log real quick. /// /// protected override void OnCustom(BridgeRead read) { Logger.Log(read.String()); } /// /// Good to keep track if stuff goes out of hand. Literally. /// /// protected override void OnUnhandled(BridgeRead read) { } } } ``` -------------------------------- ### Queue and Get Image Example Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/image-db-module.md Use `Queue` to add an image by key and URL, and `GetImage` to retrieve its ID. Always check `HasImage(key)` before UI usage for compatibility. ```csharp imageDb.Queue("logo", "https://mydomain.com/logo.png"); var id = imageDb.GetImage("logo"); ``` -------------------------------- ### Start Development Server Source: https://github.com/carboncommunity/carbon.documentation/blob/main/README.md Starts the VitePress development server. Changes are automatically applied. ```bash npm run docs:dev ``` -------------------------------- ### StackManager Example Use Case Configuration Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/optional-modules/stack-manager-module.md An example configuration demonstrating how to triple food stacks and cap specific items like scrap and refined metal. ```json { "Categories": { "Food": 3.0 }, "Items": { "scrap": 5000, "metal.refined": 1000 } } ``` -------------------------------- ### Example Server Description with Wipe Date Replacement Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/optional-modules/autowipe-module.md This example demonstrates how string replacements can be used to dynamically update the server's hostname and description with wipe date and time information. ```text My Cool Server (WIPED [WIPE_MONTH]/[WIPE_DAY]) ``` -------------------------------- ### Example Usage in Plugin Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/date-picker-module.md A practical example of using the Date Picker Module in a plugin to get and process a player's selected date. ```APIDOC ## Example Use in Plugin ```csharp datePicker.Open(player, (date) { Puts($"Player picked date {date.ToShortDateString()}"); // Use the selected date in plugin logic }); ``` ``` -------------------------------- ### Example JSON Configuration Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/config-management.md This is an example of a JSON configuration file for a plugin, showing how settings like 'Enabled', 'BypassPermission', and 'BypassGroup' can be defined. ```json // Config of the WhiteList Module from Carbon { "Enabled": false, "Config": { "BypassPermission": "whitelist.bypass", "BypassGroup": "whitelisted" }, "Version": "781308331" } ``` -------------------------------- ### Example: Browse and Select JSON Files in C# Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/file-picker-module.md Demonstrates opening the file browser to specifically select JSON files within a designated directory. Includes example callbacks for handling the selection or cancellation. ```csharp fileModule.Open(player, "Browse JSON Files", "/carbon/data", "/carbon/data", "json", onConfirm: (player, browser) => { Puts($"Confirmed: {browser.SelectedFile}"); }, onCancel: (player, browser) => { Puts("Cancelled."); }); ``` -------------------------------- ### Example Plugin Initialization Message Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/how-to-ask.md To confirm a plugin is loading, add a simple message to its initialization method. This C# example shows a message being printed to the server console. ```csharp Puts("Home plugin loaded!") ``` -------------------------------- ### Basic Automatic Patching Example Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/creating-hooks.md A simple example demonstrating the [AutoPatch] attribute for a Harmony patch. This patch targets the BasePlayer.CanSuicide method and logs a message. ```csharp using System; using HarmonyLib; using Oxide.Core.Plugins; namespace Carbon.Plugins; [Info("Collaborate", "Carbon Community", "1.0.0")] public class Collaborate : CarbonPlugin { #region Patches [AutoPatch] // [!code focus] [HarmonyPatch(typeof(BasePlayer), "CanSuicide", new Type[] { })] // [!code focus] public class Patch_1 { public static bool Prefix(BasePlayer __instance, ref bool __result) { Logger.Log("Works!"); __result = false; return false; } } #endregion } ``` -------------------------------- ### Start Carbon Bridge Server Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/bridge.md Starts the Carbon Bridge server. Ensure the password is set via command-line arguments for the server to boot. Optional IP and port can also be specified. ```csharp Carbon.Components.Bridge.Server.Start( port: Carbon.Switches.GetBridgePort(defaultValue: $"{RCon.Port + 1}").ToInt(), password: Carbon.Switches.GetBridgePassword(defaultValue: "unset"), ip: Carbon.Switches.GetBridgeIp()); ``` -------------------------------- ### Example: Handle Player Color Selection Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/color-picker-module.md Demonstrates how to use the callback from the Open method to process the selected color, such as logging it or applying it to a UI element. ```csharp colorPicker.Open(player, (hex, raw, alpha) => { Puts($ ``` -------------------------------- ### Full Plugin Structure with Configuration Management Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/config-management.md A complete example of a Carbon plugin demonstrating configuration class definition, loading, saving, updating, and integration into plugin logic. ```csharp using Newtonsoft.Json; using Oxide.Core; namespace Oxide.Plugins; [Info("CoolPlugin", "Bubbafett", "1.0.1")] [Description("Cool plugin that tells players about cool permissions.")] public class ConfigExample : RustPlugin { #region Config public Configuration PluginConfig; public class Configuration { [JsonProperty(PropertyName = "Version (DO NOT CHANGE)", Order = int.MaxValue)] public VersionNumber Version = new(1, 0, 1); [JsonProperty(PropertyName = "Permission")] public string UsePermission = "CoolPlugin.use"; [JsonProperty(PropertyName = "Permission Enabled")] public bool IsEnabled = true; } protected override void LoadDefaultConfig() => PluginConfig = new Configuration(); protected override void SaveConfig() => Config.WriteObject(PluginConfig, true); ``` -------------------------------- ### Example: Handling Player Date Selection in C# Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/date-picker-module.md Demonstrates how to use the date picker's callback to process the date selected by a player and log it to the console. This shows a practical application of the `Open` method. ```csharp datePicker.Open(player, (date) => { Puts($ ``` ```csharp Player picked date {date.ToShortDateString()}'); // Use the selected date in plugin logic }); ``` -------------------------------- ### Get Player Session in C# Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/admin-module.md Provides an example of how to retrieve a player's session object from the Admin module. This session object can be used to store and retrieve dynamically assigned content mapped to players interacting with the admin panel. ```csharp var session = Admin.GetPlayerSession(player); var myValue = session.GetStorage(tab, "my_key", @default: defaultValue); ``` -------------------------------- ### Install Rust Server Mods with LinuxGSM Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/linux-gsm.md Use this command to install mods for your Rust server via LinuxGSM. You will be prompted to select 'rustcarbon' from a list of available mods. ```bash ./rustserver mods-install ``` -------------------------------- ### Example Compiler Error with Method Not Found Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/how-to-ask.md When trying a different method, include the resulting compiler error. This example shows a C# error indicating a method and its extension methods are not found. ```csharp [CS1061] 'Player' does not contain a definition for 'HasPerm' and no accessible extension method could be found. ``` -------------------------------- ### Registering Messages Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/localization.md Register messages for a specific language using `lang.RegisterMessages`. This example registers a 'Hello' message for English. ```cs lang.RegisterMessages(new Dictionary { ["Hello"] = "Hello there!", }, this, "en"); ``` -------------------------------- ### Handling a Chat Command with Localization Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/localization.md This is an example of a chat command handler that uses localized messages for feedback. ```csharp private void CmdHello(BasePlayer player, string command, string[] args) { if(!permission.UserHasPermission(player.UserIDString, PermUse)) { LangMessage(player, "NoPerm"); return; } LangMessage(player, "Hello"); LangMessage(player,"Welcome", player.displayName); } ``` -------------------------------- ### Create Empty Container with Steam Icon Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md An example demonstrating how to create an empty container and set a Steam avatar as its icon. This is useful for displaying player avatars. ```csharp // Example cui.v2.CreateEmptyContainer(mainPanel, add: true).SetOffset(new LuiOffset(0, 0, 256, 256)).SetSteamIcon(564345673); ``` -------------------------------- ### Get All Groups Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/permissions.md Retrieve a list of all available permission groups on the server. ```csharp var groups = permission.GetGroups(); ``` -------------------------------- ### Using Dynamic Messages Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/localization.md Call the dynamic `LangMessage` overload to send personalized greetings. This example sends a welcome message including the player's display name. ```cs LangMessage(player,"Welcome", player.displayName); ``` -------------------------------- ### Example Lang File Structure Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/localization.md This JSON structure defines message keys and their corresponding string values for different languages. It supports string replacement using placeholders like {0}. ```json { "cooldown_player": "You're cooled down. Please wait {0}.", "unknown_chat_cmd_1": "Unknown command: {0}", "unknown_chat_cmd_2": "Unknown command: {0}\nSuggesting: {1}", "unknown_chat_cmd_separator_1": ", ", "unknown_chat_cmd_separator_2": " or ", "no_perm": "You don't have any of the required permissions to run this command.", "no_group": "You aren't in any of the required groups to run this command.", "no_auth": "You don't have the minimum auth level [{0}] required to execute this command [your level: {1}]." } ``` -------------------------------- ### Example Error Message in Console Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/how-to-ask.md When reporting errors, include exact console messages. This example shows a C# compiler error related to a missing method definition. ```csharp [CS0117] 'Player' does not contain a definition for 'HasPermission' ``` -------------------------------- ### Format Time Left Examples Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/custom-vitals-manager.md Demonstrates various format strings for displaying remaining time. Use tokens like 's', 'ss', 'm', 'mm', 'h', 'hh', 'd', 'dd' for time components. Double-letter tokens are zero-padded, single-letter tokens are not. Literal characters can be inserted using '\\'. ```plaintext {timeleft:} ``` ```plaintext {timeleft:hh\:mm\:ss} ``` ```plaintext {timeleft:h\:mm\:ss} ``` ```plaintext {timeleft:mm\:ss} ``` ```plaintext {timeleft:m\:ss} ``` ```plaintext {timeleft:ss} ``` ```plaintext {timeleft:s} ``` ```plaintext {timeleft:m\m\ s\s} ``` ```plaintext {timeleft:h\h\ m\m\ s\s} ``` ```plaintext {timeleft:d\d\ h\h\ m\m\ s\s} ``` -------------------------------- ### Advanced Automatic Patching with Options Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/creating-hooks.md This example shows advanced usage of the [AutoPatch] attribute, including options like IsRequired, Order, and PatchSuccessCallback for more control over patch application. ```csharp using System; using HarmonyLib; using Oxide.Core.Plugins; namespace Carbon.Plugins; [Info("Collaborate", "Carbon Community", "1.0.0")] public class Collaborate : CarbonPlugin { #region Patches public void OnPatchComplete() { // Run special code here only if the patch is successful } [AutoPatch ( // Unload plugin if patch fails // [!code focus] IsRequired = true, // [!code focus] // Specify at what time on the plugin's initialization should the patch apply // [!code focus] Order = AutoPatchAttribute.Orders.AfterOnServerInitialized, // [!code focus] PatchSuccessCallback = nameof(OnPatchComplete))] [HarmonyPatch(typeof(BasePlayer), "CanSuicide", new Type[] { })] public class Patch_1 { public static bool Prefix(BasePlayer __instance, ref bool __result) { Logger.Log("Works!"); __result = false; return false; } } #endregion } ``` -------------------------------- ### Open File Browser UI in C# Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/file-picker-module.md Initiates the in-game file browser for a player. Specify the UI title, starting directory, directory limit, file extension filter, and callback functions for confirmation and cancellation. An optional callback can provide extra file information. ```csharp fileModule.Open(player, "Title", "start/path", "path/limit", "json", onConfirm: (player, browser) => { Puts($"Selected file: {browser.SelectedFile}"); }, onCancel: (player, browser) => { Puts("File selection cancelled."); }); ``` -------------------------------- ### Initializing Plugin and Commands Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/localization.md Initialize the plugin by adding chat commands and registering permissions. This sets up the 'hi' command and the 'HelloThere.use' permission. ```cs using System.Collections.Generic; public const string PermUse = "HelloThere.use"; protected override void LoadDefaultMessages() { lang.RegisterMessages(new Dictionary { ["Hello"] = "Hello there!", ["NoPerm"] = "You do not have permission to use this command.", }, this, "en"); } private void Init() { cmd.AddChatCommand("hi", this, nameof(CmdHello)); permission.RegisterPermission(PermUse, this); } ``` -------------------------------- ### Preview Documentation Build Source: https://github.com/carboncommunity/carbon.documentation/blob/main/README.md Previews the documentation site after it has been built using the `docs:build` command. ```bash npm run docs:preview ``` -------------------------------- ### Define Basic Configuration Class Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/config-management.md Create a C# class to hold your plugin's configuration settings. It's recommended to place this within a `#region` for organization. ```csharp #region Config public class Configuration { } #endregion ``` -------------------------------- ### Build Documentation Site Source: https://github.com/carboncommunity/carbon.documentation/blob/main/README.md Builds the static documentation site for deployment. This ensures the site can be deployed to GitHub Pages. ```bash npm run docs:build ``` -------------------------------- ### Opening the Date Picker UI Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/date-picker-module.md Demonstrates how to open the date picker UI for a player and handle the selected date via a callback. ```APIDOC ## Open the Picker ```csharp datePicker.Open(player, (date) => { // Handle date picked by player }); ``` - `player` – The `BasePlayer` to open the UI for. - `onDatePicked` – A callback invoked when the player selects a date. Returns: - `date` – The selected `DateTime` object. ``` -------------------------------- ### Create a Basic Oxide Plugin Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/creating-your-first-plugin.md Use RustPlugin as the base class for standard Oxide plugins. Ensure the namespace and attributes are correctly set. ```csharp namespace Oxide.Plugins; [Info("MyPlugin", "", "1.0.0")] [Description("")] public class MyPlugin : RustPlugin { private void OnServerInitialized() { Puts("Hello world!"); } } ``` -------------------------------- ### Get Group Parent Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/permissions.md Retrieve the parent group of a specified permission group. ```csharp var parent = permission.GetGroupParent("mygroup"); ``` -------------------------------- ### Get Group Rank Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/permissions.md Retrieve the rank value of a specified permission group. ```csharp var rank = permission.GetGroupRank("mygroup"); ``` -------------------------------- ### Get Group Display Name Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/permissions.md Retrieve the display name of a specified permission group. ```csharp var displayName = permission.GetGroupTitle("mygroup"); ``` -------------------------------- ### Create a ClientEntity Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/client-entities.md Use ClientEntity.Create to instantiate a new client-side entity. Provide the prefab path, position, and rotation. Optional parameters include a custom ProtoBuf.Entity, netId, and group. ```csharp var entity = ClientEntity.Create( "assets/prefabs/deployable/chair/chair.deployed.prefab", position, rotation ); ``` -------------------------------- ### Initialize CUI Handler Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md Instantiate the CUI system using an existing CuiHandler. This is the first step to interacting with LUI. ```csharp using CUI cui = new CUI(CuiHandler); ``` -------------------------------- ### Create Panel Aliases Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md Demonstrates the various aliases available for creating a panel, highlighting differences in parameter requirements based on position and container type. ```csharp CreatePanel(string parent, LuiPosition position, LuiOffset offset, ...); // Base CreatePanel(string parent, LuiOffset offset, ...); // When position is None, we don't need to include it in method. CreatePanel(LuiContainer container, LuiPosition position, LuiOffset offset, ...); // Same as first, but we can just put the element we created previously without name knowledge. CreatePanel(LuiContainer container, LuiOffset offset, ...); // Same as second, but we can just put the element we created previously without name knowledge. ``` -------------------------------- ### Remove Rust Server Mods with LinuxGSM Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/linux-gsm.md Execute this command to remove mods from your Rust server installation managed by LinuxGSM. ```bash ./rustserver mods-removes ``` -------------------------------- ### Update Rust Server Mods with LinuxGSM Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/linux-gsm.md Run this command to update all installed mods for your Rust server using LinuxGSM. ```bash ./rustserver mods-update ``` -------------------------------- ### Load and Update Configuration Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/config-management.md Loads the plugin configuration and checks if an update is needed based on the version number. Prints a warning if the configuration is outdated and updates it. ```csharp protected override void LoadConfig() { base.LoadConfig(); PluginConfig = Config.ReadObject(); if (PluginConfig == null) { PluginConfig = new Configuration(); SaveConfig(); return; } UpdateConfig(); } ``` ```csharp private void UpdateConfig() { if (PluginConfig.Version >= Version) return; PrintWarning("Outdated configuration file detected. Updating..."); PluginConfig.IsEnabled = true; PluginConfig.Version = Version; SaveConfig(); } ``` -------------------------------- ### Get Group Permissions Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/permissions.md Retrieve all permissions associated with a specific group. The 'parents' parameter determines if inherited permissions are included. ```csharp var permissions = permission.GetGroupPermissions("mygroup", false); // 'false' is the value for the "parents" parameter. // When true, it will return all permissions, // including the parent permissions "mygroup" group is a part of. // When false, it will only return "mygroup" permissions. ``` -------------------------------- ### Player Session Management Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/admin-module.md This snippet demonstrates how to get a player's session and store/retrieve data associated with them within the admin panel. ```APIDOC ## Player Session A very handy tool that allows you to store dynamically assigned content mapped to players that are interacting with the panel. ```csharp var session = Admin.GetPlayerSession(player); var myValue = session.GetStorage(tab, "my_key", @default: defaultValue); ``` The `tab` and `@default` value is optional, you may globally store dynamically assigned content mapped to player sessions by setting the `tab` to `null`. ``` -------------------------------- ### Access Color Picker Module Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/color-picker-module.md Retrieve an instance of the ColorPickerModule to interact with its functionalities. This is the standard way to get the module within a plugin. ```csharp var colorPicker = Carbon.Base.BaseModule.GetModule(); ``` -------------------------------- ### Access Date Picker Module in C# Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/date-picker-module.md Retrieve an instance of the DatePickerModule to interact with its functionalities. This is the standard way to get the module within your plugin. ```csharp var datePicker = Carbon.Base.BaseModule.GetModule(); ``` -------------------------------- ### Update Specific UI Field Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md Allows updating a specific field of a UI element by chaining methods. This example shows setting the font type. ```csharp cui.v2.Update(string name).SetTextFont(CUI.Handler.FontTypes font); ``` -------------------------------- ### Create Simple Panel Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md Generates a basic colored panel at a specified position and offset. Random names are generated by default; disable this by setting `cui.v2.generateNames = false;` and manually assign names. ```csharp cui.v2.CreatePanel(string parent, LuiPosition position, LuiOffset offset, string color, string name = ""); ``` -------------------------------- ### Panel Helper Methods Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md Provides helper methods for setting the material and color of a panel after its creation. ```csharp .SetColor(string color); .SetMaterial(string material); ``` -------------------------------- ### Create ClientEntity Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/client-entities.md Creates a new ClientEntity with a specified prefab, position, and rotation. Optional parameters include a custom ProtoBuf.Entity, netId, and group. ```APIDOC ## Create ClientEntity ### Description Creates a new ClientEntity with a specified prefab, position, and rotation. Optional parameters include a custom ProtoBuf.Entity, netId, and group. ### Method Signature ```csharp ClientEntity.Create(string prefabPath, Vector3 position, Vector3 rotation, ProtoBuf.Entity? entity = null, int? netId = null, string? group = null) ``` ### Example ```csharp var entity = ClientEntity.Create( "assets/prefabs/deployable/chair/chair.deployed.prefab", position, rotation ); ``` ``` -------------------------------- ### Retrieve Stored Image ID Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/image-db-module.md Get the internal image ID associated with a given key from the Image Database Module. This ID can be used for further operations or references. ```csharp var imageId = imageDb.GetImage("my-key"); ``` -------------------------------- ### Download Carbon Template Project Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/creating-your-project.md Use this link to download the Visual Studio 2022 project template for Carbon. It includes a self-contained server and development environment. ```html ``` -------------------------------- ### Define Configuration Class Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/config-management.md Defines the structure for plugin configuration, including version, permission settings, and an enable flag. Use this to set default values for new configuration options. ```csharp public class Configuration { [JsonProperty(PropertyName = "Version (DO NOT CHANGE)", Order = int.MaxValue)] public VersionNumber Version = new(1, 0, 1); [JsonProperty(PropertyName = "Permission")] public string UsePermission = "CoolPlugin.use"; [JsonProperty(PropertyName = "Permission Enabled")] public bool IsEnabled = true; } ``` -------------------------------- ### Add Raw Image Data Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/image-db-module.md Add raw image data directly to the Image Database Module. This is useful when you have image bytes already loaded, for example, from a file. ```csharp var imagePath = "carbon/data/someimage.png"; var bytes = File.ReadAllBytes(imagePath); imageDb.AddImage("my-key", bytes); ``` -------------------------------- ### Dynamic Message Formatting Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/localization.md Create an overload for `LangMessage` that accepts string arguments for dynamic message formatting using `string.Format`. This allows messages like 'Welcome to the server, {0}!' to be personalized. ```cs private void LangMessage(BasePlayer player, string key, params string[] args) { player.ChatMessage(string.Format(lang.GetMessage(key, this, player.UserIDString),args)); } ``` -------------------------------- ### Check Player Permissions in C# Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/how-to-read.md This C# code checks if a player has a specific permission before executing an action. It's provided as an example of how to interpret code snippets within documentation. ```csharp // This is beautiful and easy to understand. // The author put it here for a reason. if (player.HasPermission("teleport.home")) { Puts("Player has permission!"); } ``` -------------------------------- ### Registering a Permission and Chat Command Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/localization.md This snippet shows how to register a permission and a chat command for your plugin. ```csharp cmd.AddChatCommand("hi", this, nameof(CmdHello)); permission.RegisterPermission(PermUse, this); ``` -------------------------------- ### Create Image from File Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md Creates an image from a specified PNG file. Useful for custom image assets. Parameters include parent, position, offset, and the PNG file path. ```csharp cui.v2.CreateImage(string parent, LuiPosition position, LuiOffset offset, string png, string color = LuiColors.White, string name = ""); ``` -------------------------------- ### Customize Specific Gather Yields Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/optional-modules/gather-manager-module.md Adjusts the gather yield for specific items like 'stones' and 'wood'. This example reduces stone yield by 25% and increases wood yield by 25%. ```json { "Gather": { "*": 1.0, "stones": 0.75, "wood": 1.25 } } ``` -------------------------------- ### Create URL Image Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md Creates an image element by loading it directly from a URL. Be aware of potential download times. Parent, position, offset, and URL are required. ```csharp cui.v2.CreateUrlImage(string parent, LuiPosition position, LuiOffset offset, string url, string color = LuiColors.White, string name = ""); ``` -------------------------------- ### Add and Manage Player-Specific Vitals Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/custom-vitals-manager.md Shows how to add a vital to an individual player and how to clear all vitals for a player. Includes a console command example for updating a player's vital dynamically. ```csharp using Carbon.Components; using Carbon.Modules; public readonly ImageDatabaseModule ImageDatabase = BaseModule.GetModule(); public CustomVitalManager.PlayerIdentifiableVital playerVital; private void OnServerInitialized() { var self = BasePlayer.Find("Raul"); var vital = CustomVitalManager.RentVitalInfo( icon: ImageDatabase.GetImageString("reload"), iconColor: Color.yellow.WithAlpha(.6f), backgroundColor: Color.black.WithAlpha(.9f), leftText: "Standing by...", leftTextColor: Color.white.WithAlpha(.6f)); playerVital = CustomVitalManager.AddVital(self, vital); } private void Unload() { var self = BasePlayer.Find("Raul"); CustomVitalManager.ClearVitals(self); } [ConsoleCommand("sillygoosery")] private void sillygoosery(ConsoleSystem.Arg arg) { var player = arg.Player(); player.Ragdoll(); playerVital.info.icon = ImageDatabase.GetImageString("star"); playerVital.info.leftText = "Ragdolling"; playerVital.info.backgroundColor = Color.red.WithAlpha(.6f); playerVital.info.rightText = "{timeleft:ss}s"; playerVital.info.rightTextColor = Color.white; playerVital.SetTimeLeft(5); // Restarts the timer of the vital playerVital.SendUpdate(); timer.In(5f, () => { playerVital.info.icon = ImageDatabase.GetImageString("reload"); playerVital.info.leftText = "Standing by..."; playerVital.info.rightText = string.Empty; playerVital.info.backgroundColor = Color.black.WithAlpha(.9f); playerVital.SendUpdate(); }); } ``` -------------------------------- ### Protected Command for Security Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/commands.md ProtectedCommand uses randomized identifiers to prevent unauthorized access, ideal for commands meant for UI interaction. Use Community.Protect to get the callable command string. ```csharp [ProtectedCommand("mydopecommand")] private void SuperSecret(ConsoleSystem.Arg arg) { Puts("How'd you do that!?"); } // Demonstration private void OnServerInitialized() { var callableCommand = Community.Protect("mydopecommand"); Puts($"{callableCommand}"); // Command that can be called by the clients: // carbonprotecc_npomamd1mompd8d2 ConsoleSystem.Run(ConsoleSystem.Option.Server, callableCommand); } ``` -------------------------------- ### Manual Harmony Patching Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/creating-hooks.md Demonstrates manual management of Harmony patches within a Carbon plugin. This involves initializing Harmony, patching all assemblies, and unpatching on unload. Use with caution. ```csharp using System; using HarmonyLib; namespace Carbon.Plugins; [Info("Collaborate", "Carbon Community", "1.0.0")] public class Collaborate : CarbonPlugin { public Harmony _PATCH; public const string DOMAIN = "com.carbon.mypatch"; private void Init() { _PATCH = new Harmony(DOMAIN); _PATCH.PatchAll(Assembly.GetExecutingAssembly()); Puts("Patched."); } private void Unload() { _PATCH.UnpatchAll(DOMAIN); Puts("Unpatched."); } #region Patches [HarmonyPatch(typeof(BasePlayer), "CanSuicide", new Type[] { })] public class Patch_1 { public static bool Prefix(BasePlayer __instance, ref bool __result) { Logger.Log("Works!"); __result = false; // Returning false will prohibit the original code from executing // Only applies to Prefixes return false; } } #endregion } ``` -------------------------------- ### Update Carbon Server Files Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/creating-your-project.md Run this batch file to download the latest files required for Carbon to function. Different files exist for various branches like production, preview, and edge. ```batch update_edge.bat ``` ```batch update_production.bat ``` ```batch update_preview.bat ``` ```batch update_rustbeta_staging.bat ``` -------------------------------- ### Implement Harmony Prefix Patch Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/creating-hooks.md This example shows a Harmony Prefix patch that uses HookCaller.CallStaticHook to invoke a hook with a numeric identifier. It returns false to prevent the original code from executing if the hook returns a boolean. ```csharp public static bool Prefix(BasePlayer ply, ref PatrolHelicopterAI __instance, out bool __result) { if (HookCaller.CallStaticHook(1610282469, __instance, ply) is bool boolean) // [!code focus] { __result = boolean; // Disallow original code from executing return false; } __result = default; // Allow original code to execute return true; } ``` -------------------------------- ### Raw Image Helper Methods Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md Helper methods for customizing raw image elements, including setting images from URLs, Steam IDs, sprites, or materials. ```csharp .SetUrlImage(string url = null, string color = null) ``` ```csharp .SetSteamIcon(ulong steamid, string color = null); ``` ```csharp .SetRawSprite(string sprite, string color = null); ``` ```csharp .SetRawMaterial(string material, string color = null); ``` -------------------------------- ### Load Plugin Configuration Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/config-management.md Override `LoadConfig` to load the configuration. It ensures a valid configuration is always available by creating and saving a new one if loading fails. ```csharp using Oxide.Core; using Newtonsoft.Json; #region Config public Configuration PluginConfig; public class Configuration { [JsonProperty(PropertyName = "Version (DO NOT CHANGE)", Order = int.MaxValue)] public VersionNumber Version = new(1, 0, 0); [JsonProperty(PropertyName = "Permission")] public string UsePermission = "CoolPlugin.use"; } protected override void LoadDefaultConfig() => PluginConfig = new Configuration(); protected override void SaveConfig() => Config.WriteObject(PluginConfig, true); protected override void LoadConfig() { base.LoadConfig(); PluginConfig = Config.ReadObject(); if (PluginConfig == null) { PluginConfig = new Configuration(); SaveConfig(); return; } } #endregion ``` -------------------------------- ### Opening a User Info Modal Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/modal-module.md Opens a modal to collect user information, including a required string for 'Name' and an optional integer for 'Age'. The onConfirm callback processes the collected data, and the onCancel callback handles modal cancellation. ```csharp var fields = new Dictionary { ["name"] = ModalModule.Modal.Field.Make("Name", ModalModule.Modal.Field.FieldTypes.String, required: true), ["age"] = ModalModule.Modal.Field.Make("Age", ModalModule.Modal.Field.FieldTypes.Integer) }; modalModule.Open(player, "User Info", fields, onConfirm: (player, modal) => { var name = modal.Get("name"); var age = modal.Get("age"); Puts($"{player.displayName} entered: {name}, {age}"); }, onCancel: () => { Puts("Modal was cancelled."); }); ``` -------------------------------- ### Declare Public Configuration Instance Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/config-management.md Declare a public instance of your `Configuration` class within your plugin. This instance will be used to store and access the loaded configuration data throughout your plugin. ```csharp using Oxide.Core; using Newtonsoft.Json; #region Config public Configuration PluginConfig; public class Configuration { [JsonProperty(PropertyName = "Version (DO NOT CHANGE)", Order = int.MaxValue)] public VersionNumber Version = new(1, 0, 0); [JsonProperty(PropertyName = "Permission")] public string UsePermission = "CoolPlugin.use"; } #endregion ``` -------------------------------- ### Queue Image for Download Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/image-db-module.md Queue an image from a URL to be downloaded and stored by the Image Database Module. The image will be associated with the provided key. ```csharp imageDb.Queue("my-key", "https://example.com/image.png"); ``` -------------------------------- ### Partial Plugin Files Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/zip-script-packages.md Additional files for a ZIP script package must share the same namespace and partial class name as the primary file. The base type definition is optional in these partial files. ```csharp namespace Carbon.Plugins; public partial class MyPlugin { [Command("yoyo")] private void CommandBeLike(BasePlayer player, string cmd, string[] args) { var test = "asdasd"; Puts($ ``` -------------------------------- ### Universal Command Handling Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/commands.md Universal commands can be accessed via chat, F1 console, server console, or RCon. Always check for a null player when handling these commands. ```csharp [Command("myunicommand")] private void MyUniversalCommand(BasePlayer player, string command, string[] args) { if (player == null) { Puts("woo Wee!"); } else { player.ChatMessage("Wee woo!"); } } ``` -------------------------------- ### Configure Web Panel Accounts and Bridge Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/news/carbon/october-25-update.md This JSON configuration file defines the settings for the Carbon Web Panel, including enabling the Bridge server, its IP and port, and defining user accounts with specific permissions. Reload the config using `c.webpanel.loadcfg` to apply changes. ```json { "Enabled": true, "BridgeServer": { "Ip": "localhost", "Port": 28608 }, "WebAccounts": [ { "Name": "owner", "Password": "BMjgFMH", "Permissions": { "console_view": true, "console_input": true, "chat_view": true, "chat_input": true, "players_view": true, "players_ip": true, "players_inventory": true, "entities_view": true, "entities_edit": true, "permissions_view": true, "permissions_edit": true } }, { "Name": "guest", "Password": "guest", "Permissions": { "console_view": false, "console_input": false, "chat_view": true, "chat_input": true, "players_view": true, "players_ip": false, "players_inventory": false, "entities_view": false, "entities_edit": false, "permissions_view": false, "permissions_edit": false } } ] } ``` -------------------------------- ### Image Helper Methods Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md A collection of helper methods to customize image elements after creation, such as setting color, material, image type, or specific image sources. ```csharp .SetColor(string color); ``` ```csharp .SetMaterial(string material); ``` ```csharp .SetImageType(UnityEngine.UI.Image.Type imageType); ``` ```csharp .SetSprite(string sprite = null, string color = null, UnityEngine.UI.Image.Type imageType = Image.Type.Simple); ``` ```csharp .SetImage(string png = null, string color = null); ``` ```csharp .SetItemIcon(int itemid, ulong skinid); ``` -------------------------------- ### C# Extension Template Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/extensions.md This C# code provides a template for creating a Carbon extension. It includes the necessary using statements, namespace, and the `ICarbonExtension` interface with methods for loading, awakening, and unloading the extension. It also demonstrates subscribing to server initialization events. ```csharp #if CARBON using System; using API.Assembly; using Carbon; namespace Extension { public class ExtensionEntrypoint : ICarbonExtension { public void OnLoaded(EventArgs args) { Community.Runtime.Events.Subscribe(API.Events.CarbonEvent.OnServerInitialized, arg => { try { // Do something wild } catch (Exception ex) { Logger.Error("Failed doing something wild.", ex); } }); } public void Awake(EventArgs args) { // Do something wild } public void OnUnloaded(EventArgs args) { // Do something wild } } } #endif ``` -------------------------------- ### Adding Buttons Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md Method for creating clickable buttons that can execute commands when interacted with. ```APIDOC ## Adding Buttons ```csharp cui.v2.CreateButton(string parent, LuiPosition position, LuiOffset offset, string command, string color, bool isProtected = true, string name = ""); ``` Creates a clickable button that the player can interact with. By default, commands in buttons are protected by Carbon command protection, so keep that in mind while assigning a command. List of helper methods: ```csharp .SetButton(string command = null, string color = null) .SetButtonColors(string color = null, string normalColor = null, string highlightedColor = null, string pressedColor = null, string selectedColor = null, string disabledColor = null, float colorMultiplier = -1, float fadeDuration = -1); .SetButtonMaterial(string material); .SetButtonSprite(string sprite, UnityEngine.UI.Image.Type imageType = Image.Type.Simple); .SetButtonClose(string close); ``` ``` -------------------------------- ### Conditional Compilation for Frameworks Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/conditionals.md Use #if CARBON to include code that runs only on Carbon, and #if !CARBON for code that runs on other frameworks like Oxide. ```csharp private void OnServerInitialized() { #if CARBON Puts("This is called on Carbon."); #endif #if !CARBON Puts("This is called on Oxide."); #endif } ``` -------------------------------- ### Enable Debugger in doorstop_config.ini Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/local-server-hosting.md Edit this INI file to enable debugging for plugin development. Ensure you back up changes before running update scripts, as they may overwrite this file. ```ini [UnityMono] debug_enabled=true debug_suspend=true debug_address=127.0.0.1:5337 ``` -------------------------------- ### Button Helper Methods Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/lightweight-ui.md Provides methods to customize button appearance and behavior, including setting commands, colors, materials, and sprites. ```csharp .SetButton(string command = null, string color = null) ``` ```csharp .SetButtonColors(string color = null, string normalColor = null, string highlightedColor = null, string pressedColor = null, string selectedColor = null, string disabledColor = null, float colorMultiplier = -1, float fadeDuration = -1); ``` ```csharp .SetButtonMaterial(string material); ``` ```csharp .SetButtonSprite(string sprite, UnityEngine.UI.Image.Type imageType = Image.Type.Simple); ``` ```csharp .SetButtonClose(string close); ``` -------------------------------- ### Register Permissions Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/devs/features/permissions.md Register new permissions for your plugin. This is typically done during plugin initialization. ```csharp private void Init() { permission.RegisterPermission("myplugin.admin", this); permission.RegisterPermission("myplugin.use", this); } ``` -------------------------------- ### Use Code Blocks for Code and Logs Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/how-to-ask.md Always enclose code, configuration, and console logs in triple-backtick code blocks to preserve indentation and enable syntax highlighting. ```csharp // This is beautiful and easy to read. if (player.HasPermission("teleport.home")) { Puts("Player has permission!"); } ``` -------------------------------- ### Create Plugin Class with Metadata Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/tutorials/beginners-guide/first-plugin.md Defines the main plugin class, inheriting from CarbonPlugin. Includes essential metadata like plugin name, author, version, and a description. ```csharp namespace Carbon.Plugins; [Info("MyFirstPlugin", "Bubbafett", "1.0.0")] [Description("A simple plugin that prints a message when loaded.")] public class MyFirstPlugin : CarbonPlugin { } ``` -------------------------------- ### Admin Module Configuration Source: https://github.com/carboncommunity/carbon.documentation/blob/main/docs/owners/modules/admin-module.md This JSON object outlines the configuration settings for the Admin module. It includes options for enabling the module, defining open commands, setting minimum authentication levels, and controlling the visibility of specific tabs like Entities and Plugins. ```json { "Enabled": true, "Config": { "OpenCommands": [ "cp", "cpanel" ], "MinimumAuthLevel": 2, "DisableEntitiesTab": true, "DisablePluginsTab": false, "DisableConsole": false, "SpectatingInfoOverlay": true, "SpectatingEndTeleportBack": false, "QuickActions": [] }, "Version": "3927179163" } ```