NAV Navbar
csharp
  • Getting Started
  • Universal Hooks
  • Server Hooks
  • Player Hooks
  • Entity Hooks
  • Item Hooks
  • Structure Hooks
  • Library Functions
  • Timers (Basic)
  • Web Requests
  • Plugin Calling
  • Getting Started

    namespace Oxide.Plugins
    {
        [Info("EpicStuff", "Unknown", 0.1)]
        [Description("Makes epic stuff happen")]
    
        class EpicStuff : RustLegacyPlugin
        {
            // The rest of the code and magic
        }
    }
    

    The Title variable is what defines your plugin. This should be a unique codename or short description such as Pets.

    The Author variable is used to show who made the plugin. This should match your OxideMod.org username if releasing.

    The Version variable is used to tell if the plugin is outdated or not, and is incremented with each release. Semantic Versioning recommended.

    The Description variable helps explain to users what your plugin does, in case the title isn't enough. Make it good, but not too long!

    Universal Hooks

    Available for all supported games

    7 Days to Die Blockstorm Hurtworld Reign of Kings Rust Rust Legacy The Forest Unturned

    Init

    void Init()
    {
        Puts("Init works!");
    }
    

    Loaded

    void Loaded()
    {
        Puts("Loaded works!");
    }
    

    Unload

    void Unload()
    {
        Puts("Save files, destroy timers, etc");
    }
    

    LoadDefaultConfig

    protected override void LoadDefaultConfig()
    {
        Puts("Default configuration created");
    }
    

    LoadDefaultMessages

    private new void LoadDefaultMessages()
    {
        lang.RegisterMessages(new Dictionary<string, string>
        {
            ["Example"] = "This is an example message!",
            ["AnotherExample"] = "Here is another example"
        }, this);
    }
    

    OnFrame

    void OnFrame()
    {
        Puts("OnFrame works!");
    }
    

    OnPluginLoaded

    void OnPluginLoaded(Plugin name)
    {
        Puts($"Plugin '{name}' has been loaded");
    }
    

    OnPluginUnloaded

    void OnPluginUnloaded(Plugin name)
    {
        Puts($"Plugin '{name}' has been unloaded");
    }
    

    OnServerInitialized

    void OnServerInitialized()
    {
        Puts("OnServerInitialized works!");
    }
    

    OnServerSave

    void OnServerSave()
    {
        Puts("OnServerSave works!");
    }
    

    OnPermissionRegistered

    void OnPermissionRegistered(string name, Plugin owner)
    {
        Puts($"Permission '{name}' has been registered {(owner != null ? $"for {owner.Title}" : "")}");
    }
    

    OnGroupPermissionGranted

    void OnGroupPermissionGranted(string name, string perm)
    {
        Puts($"Group '{name}' granted permission: {perm}");
    }
    

    OnGroupPermissionRevoked

    void OnGroupPermissionRevoked(string name, string perm)
    {
        Puts($"Group '{name}' revoked permission: {perm}");
    }
    

    OnGroupCreated

    void OnGroupCreated(string name)
    {
        Puts($"Group '{name}' created!");
    }
    

    OnGroupDeleted

    void OnGroupDeleted(string name)
    {
        Puts($"Group '{name}' deleted!");
    }
    

    OnGroupTitleSet

    void OnGroupTitleSet(string name, string title)
    {
        Puts($"Title '{title}' set on group '{name}'");
    }
    

    OnGroupRankSet

    void OnGroupRankSet(string name, int rank)
    {
        Puts($"Rank '{rank}' set on group '{name}'");
    }
    

    OnGroupParentSet

    void OnGroupParentSet(string name, string parent)
    {
        Puts($"Parent '{parent}' set on group '{name}'");
    }
    

    OnUserNameUpdated

    void OnUserNameUpdated(string id, string oldName, string newName)
    {
        Puts($"Player name changed from {oldName} to {newName} for ID {id}");
    }
    

    OnUserGroupAdded

    void OnUserGroupAdded(string id, string name)
    {
        Puts($"User '{id}' added to group: {name}");
    }
    

    OnUserGroupRemoved

    void OnUserGroupRemoved(string id, string name)
    {
        Puts($"Player '{id}' removed from group: {name}");
    }
    

    OnUserPermissionGranted

    void OnUserPermissionGranted(string id, string perm)
    {
        Puts($"Player '{id}' granted permission: {perm}");
    }
    

    OnUserPermissionRevoked

    void OnUserPermissionRevoked(string id, string perm)
    {
        Puts($"Player '{id}' revoked permission: {perm}");
    }
    

    OnUserKicked

    void OnUserKicked(IPlayer player, string reason)
    {
        Puts($"Player {player.Name} ({player.Id}) was kicked");
    }
    

    OnUserBanned

    void OnUserBanned(string name, string id, string address, string reason)
    {
        Puts($"Player {name} ({id}) was banned: {reason}");
    }
    

    OnUserUnbanned

    void OnUserUnbanned(string name, string id, string ip)
    {
        Puts($"Player {name} ({id}) was unbanned");
    }
    

    Server Hooks

    OnRunCommand

    void OnRunCommand(ConsoleSystem.Arg arg, bool reply)
    {
        Puts("OnRunCommand works!");
    }
    

    OnDatablocksInitialized

    void OnDatablocksInitialized()
    {
        Puts("OnDatablocksInitialized works!");
    }
    

    OnResourceNodeLoaded

    void OnResourceNodeLoaded(ResourceTarget resource)
    {
        Puts("OnResourceNodeLoaded works!");
    }
    

    Player Hooks

    OnUserApprove

    void OnUserApprove(ClientConnection connection, uLink.NetworkPlayerApproval approval, ConnectionAcceptor acceptor)
    {
        Puts("OnUserApprove works!");
    }
    

    CanClientLogin

    void CanClientLogin(ClientConnection connection, uLink.NetworkPlayerApproval approval)
    {
        Puts("CanClientLogin works!");
    }
    

    OnPlayerConnected

    void OnPlayerConnected(NetUser netUser)
    {
        Puts("OnPlayerConnected works!");
    }
    

    OnPlayerDisconnected

    void OnPlayerDisconnected(uLink.NetworkPlayer networkPlayer)
    {
        Puts("OnPlayerDisconnected works!");
    }
    

    OnPlayerSpawn

    void OnPlayerSpawn(PlayerClient client, bool usecamp, RustProto.Avatar avatar)
    {
        Puts("OnPlayerSpawn works!");
    }
    

    OnPlayerChat

    void OnPlayerChat(NetUser netUser, string message)
    {
        Puts("OnPlayerChat works!");
    }
    

    OnPlayerVoice

    void OnPlayerVoice(NetUser netUser, List<uLink.NetworkPlayer> players)
    {
        Puts("OnPlayerVoice works!");
    }
    

    OnItemCraft

    void OnItemCraft(CraftingInventory inventory, BlueprintDataBlock blueprint, int amount, ulong startTime)
    {
        Puts("OnItemCraft works!");
    }
    

    OnBlueprintUse

    void OnBlueprintUse(BlueprintDataBlock blueprint, IBlueprintItem item)
    {
        Puts("OnBlueprintUse works!");
    }
    

    OnResearchItem

    void OnResearchItem(ResearchToolItem<T> item, IInventoryItem otherItem)
    {
        Puts("OnResearchItem works!");
    }
    

    Entity Hooks

    OnAirdrop

    void OnAirdrop(Vector3 position)
    {
        Puts("OnAirdrop works!");
    }
    

    OnHurt

    void OnHurt(TakeDamage damage, DamageEvent evt)
    {
        Puts("OnHurt works!");
    }
    

    OnKilled

    void OnKilled(TakeDamage damage, DamageEvent evt)
    {
        Puts("OnKilled works!");
    }
    

    Item Hooks

    OnItemAdded

    void OnItemAdded(Inventory inventory, int slot, IInventoryItem item)
    {
        Puts("OnItemAdded works!");
    }
    

    OnItemRemoved

    void OnItemRemoved(Inventory inventory, int slot, IInventoryItem item)
    {
        Puts("OnItemRemoved works!");
    }
    

    OnItemDeployed

    void OnItemDeployed(DeployableObject deployable, IDeployableItem item)
    {
        Puts("OnItemDeployed works!");
    }
    

    Structure Hooks

    OnStructureBuilt

    void OnStructureBuilt(StructureComponent component, IStructureComponentItem item)
    {
        Puts("OnStructureBuilt works!");
    }
    

    OnStructureDecay

    void OnStructureDecay(StructureMaster master)
    {
        Puts("OnStructureDecay works!");
    }
    

    OnDoorToggle

    void OnDoorToggle(BasicDoor door, ulong timestamp, Controllable controllable)
    {
        Puts("OnDoorToggle works!");
    }
    

    Library Functions

    There are a few functions that have been added to wrap Rust Legacy functions, creating aliases of sorts to make your life easier during initial coding as well as during upgrades.

    BroadcastChat

    void OnPlayerConnected(NetUser netUser)
    {
        PrintToChat($"{netUser.displayName} has joined the server"));
    }
    

    Sends a chat message to all players.

    rust.BroadcastChat(string message, object[] args)

    BroadcastConsole

    void OnPlayerConnected(NetUser netUser)
    {
        PrintToConsole($"{netUser.displayName} has joined the server");
    }
    

    Prints a message to all players' in-game console

    rust.BroadcastConsole(string message, object[] args)

    FindPlayer

    [ChatCommand("ex")
    void Example(NetUser netUser, string command, string[] args)
    {
        NetUser target = rust.FindPlayer(args[0]);
    }
    

    Searches for an online player by name, steam id or ip. Returns a netUser if a player is found, otherwise null is returned.

    rust.FindPlayer(string nameOrSteamIdOrIp)

    PrivateBindingFlag

    rust.PrivateBindingFlag()
    

    This should not be used in C# plugins, Reflection should be used instead

    Used to get/set private methods, fields, and properties through Reflection.

    rust.PrivateBindingFlag()

    QuoteSafe

    var message = "Use /kick \"playername\" to kick player";
    message.QuoteSafe();
    

    Used to safely save text or send a message that contains quotation marks.

    rust.QuoteSafe(message)

    SendChatMessage

    void OnPlayerSpawn(NetUser netUser)
    {
        var message = "You've respawned from a terrible death";
        rust.SendChatMessage({ netUser, message });
    }
    

    Sends a chat message to specified player.

    rust.SendChatMessage(NetUser netUser, string message, object[] args)

    SendConsoleMessage

    void OnPlayerSpawn(NetUser netUser)
    {
        var message = "You've respawned from a terrible death";
        rust.SendConsoleMessage({ netUser, message });
    }
    

    Sends a console message to specified player's console.

    rust.SendConsoleMessage(NetUser netUser, string message, object[] args)

    UserIDFromPlayer

    [ChatCommand("id")]
    void ChatId(NetUser netUser, string command, string[] args)
    {
        SendReply(netUser, "Your ID is: " + netUser.userID.ToString());
    }
    

    Gets the user ID (64-bit SteamID) as a string of an online player.

    rust.UserIDFromPlayer(NetUser netUser)

    Notice

    [ChatCommand("notice")]
    void cmdNotice(NetUser netUser, string command, string[] args)
    {
        var message = "Notice Demo";
        var icon = "!";
        var duration = 4f;
        rust.Notice(netUser, message, icon, duration);
    }
    

    Sends a notice to the player at the top of the screen.

    rust.Notice(NetUser netUser, string message, string icon, float duration)

    InventoryNotice

    [ChatCommand("notice")]
    void cmdNotice(NetUser netUser, string command, string[] args)
    {
        var message = "InventoryNotice Demo";
        rust.InventoryNotice(netUser, message);
    }
    

    Sends a notice to the player on the right side of the screen right above the player's health bar.

    rust.InventoryNotice(NetUser netUser, string message)

    Timers (Basic)

    Timers are great for delaying code, allowing it to be run later.

    Single timer

    timer.Once(3f, () =>
    {
        Puts("Hello world!")
    });
    

    Executes the specified function once after the specified delay.

    Repeating timer

    timer.Repeat(5f, 0, () =>
    {
        Puts("Hello world!")
    });
    

    Executes the specified function every "delay" seconds.

    If "repeats" is specified, the function will only be called "repeats" times.

    Next frame timer

    NextFrame(() =>
    {
        Puts("Hello world!");
    });
    

    Executes the specified function at the next frame.

    Web Requests

    Web requests allow you to send a HTTP GET or POST to a specified URL.

    The request will return true if the web request was sent, false if not. The callback is called with 2 parameters - an integer HTTP response code and a string response.

    Basic Get method

    using Oxide.Core.Libraries.Covalence;
    
    namespace Oxide.Plugins
    {
        [Info("EpicStuff", "Unknown", 1.0)]
        [Description("This example illustrates how to use a GET WebRequest")]
    
        class EpicStuff : CovalencePlugin
        {
            [Command("get")]
            void GetRequest(IPlayer player, string command, string[] args)
            {
                webrequest.EnqueueGet("http://www.google.com/search?q=oxide", (code, response) => GetCallback(code, response, player), this);
            }
    
            void GetCallback(int code, string response, IPlayer player)
            {
                if (response == null || code != 200)
                {
                    Puts($"Error: {code} - Couldn't get an answer from Google for {player.Name}");
                    return;
                }
    
                Puts($"Google answered for {player.Name}: {response}");
            }
        }
    }
    

    This uses the raw connection to a web page as you would on your browser.

    Basic POST method

    using Oxide.Core.Libraries.Covalence;
    
    namespace Oxide.Plugins
    {
        [Info("EpicStuff", "Unknown", 1.0)]
        [Description("This example illustrates how to use a POST WebRequest")]
    
        class EpicStuff : CovalencePlugin
        {
            [Command("post")]
            void PostRequest(IPlayer player, string command, string[] args)
            {
                webrequest.EnqueuePost("http://www.google.com/search?q=oxide", "param1=value1&param2=value2", (code, response) => PostCallback(code, response, player), this);
            }
    
            void PostCallback(int code, string response, IPlayer player)
            {
                if (response == null || code != 200)
                {
                    Puts($"Error: {code} - Couldn't get an answer from Google for {player.Name}");
                    return;
                }
                Puts("Google answered for " + player.Name + ": " + response);
            }
        }
    }
    

    Advanced GET method

    using Oxide.Core.Libraries.Covalence;
    
    namespace Oxide.Plugins
    {
        [Info("EpicStuff", "Unknown", 1.0)]
        [Description("This example illustrates how to use a GET WebRequest")]
    
        class EpicStuff : CovalencePlugin
        {
            [Command("get")]
            void GetRequest(IPlayer player, string command, string[] args)
            {
                // Set a custom timeout (in milliseconds)
                var timeout = 200f;
    
                // Set some custom request headers (eg. for HTTP Basic Auth)
                var headers = new Dictionary<string, string> { { "header", "value" } };
    
                webrequest.EnqueueGet("http://www.google.com/search?q=oxide", (code, response) => GetCallback(code, response, player), this, headers, timeout);
            }
    
            void GetCallback(int code, string response, IPlayer player)
            {
                if (response == null || code != 200)
                {
                    Puts($"Error: {code} - Couldn't get an answer from Google for {player.Name}");
                    return;
                }
    
                Puts($"Google answered for {player.Name}: {response}");
            }
        }
    }
    

    Advanced POST method

    using Oxide.Core.Libraries.Covalence;
    
    namespace Oxide.Plugins
    {
        [Info("EpicStuff", "Unknown", 1.0)]
        [Description("This example illustrates how to use a POST WebRequest")]
    
        class EpicStuff : CovalencePlugin
        {
            [Command("post")]
            void PostRequest(IPlayer player, string command, string[] args)
            {
                // Set a timeout (in milliseconds)
                var timeout = 200f;
    
                // Set some custom request headers (eg. for HTTP Basic Auth)
                var headers = new Dictionary<string, string> { { "header", "value" } };
    
                webrequest.EnqueuePost("http://www.google.com/search?q=oxide", "param1=value1&param2=value2", (code, response) => PostCallback(code, response, player), this, headers, timeout);
            }
    
            void PostCallback(int code, string response, IPlayer player)
            {
                if (response == null || code != 200)
                {
                    Puts($"Error: {code} - Couldn't get an answer from Google for {player.Name}");
                    return;
                }
                Puts("Google answered for " + player.Name + ": " + response);
            }
        }
    }
    

    Plugin Calling

    Oxide allows you to expose methods in your plugin and make them available to other plugins. This allows you to access objects or properties from other plugins without having to replicate functionality yourself.

    Exposing a plugin's method

    namespace Oxide.Plugins
    {
        [Info("EpicStuff", "Unknown", 0.1)]
        [Description("Makes epic stuff happen")]
        class EpicStuff : CovalencePlugin
        {
            // Plugin methods can be a simple bool that is returned
            bool GetReturn()
            {
                return true;
            }
    
            // Plugin methods can take parameters and return simple types
            string TakeParam(string param, int secondParam)
            {
                if (param == "first parameter") return param;
                else return "First parameter didn't match!";
            }
    
            // To return complex types, they should first be converted
            // into builtin types (e.g. JSON.net types like JObject, JArray, etc. or builtin
            // collections like System.Collections.Generic.Dictionary)
            JObject ReturnObject()
            {
                var myObject = new JObject();
                myObject["key"] = "value";
                myObject["array"] = new JArray();
                return myObject;
            }
    
            // Plugin methods don't have to return something
            void SendMessage()
            {
                Puts("You just called the 'SendMessage' method!");
            }
        }
    }
    

    Exposing a plugin's method allows other plugins to call that method.

    For example, you could write a plugin that does some player management, then allow other plugins to "query" it to get a list of players who have certain privileges set in the original plugin.

    Calling a plugin's method

    namespace Oxide.Plugins
    {
        [Info("SecondEpicStuff", "Unknown", 0.1)]
        [Description("Makes more epic stuff happen")]
        class SecondEpicStuff : CovalencePlugin
        {
            // First, add a reference to the plugin you are trying to call
            // The name of this field needs to be the exact name of the desired plugin
            // eg. We are referencing the example plugin above which is called 'EpicStuff'
            [PluginReference]
            Plugin EpicStuff;
    
            // It's a good idea to check if the plugin you're trying to call
            // has been loaded by oxide (otherwise you can't call the method)
            void OnServerInitialized()
            {
                // Note: Trying to do this check in the plugin Init() method may
                // fail, as the plugin load order may be different each time
                if (EpicStuff == null)
                {
                    PrintWarning("Plugin 'EpicStuff' was not found!");
                }
            }
    
            void CallPlugin()
            {
                // Plugin methods return objects, so cast the API call to the type
                // you're expecting
                var getTypedReturn = (bool)EpicStuff?.Call("GetReturn");
    
                // Send parameters through as variables after the method name
                var takeParam = (string)EpicStuff?.Call("TakeParam", "param1", 1024);
    
                // Use JSON.net to process the returned object
                var returnedObject = EpicStuff?.Call("ReturnObject");
    
                // Call a plugin to do some work without returning anything
                EpicStuff?.Call("SendMessage");
            }
        }
    }
    

    Calling a plugin's method allows you to access results from another plugin.