### Handling Script Load Notifications Source: https://context7.com/facepunch/rust.modloader/llms.txt Scripts can automatically receive notifications when other scripts are loaded or unloaded through broadcasted events. This allows for dynamic setup and cleanup based on script availability. ```APIDOC ## Handling Script Load Notifications ### Description Scripts are automatically notified when other scripts are loaded or unloaded via broadcasted events, enabling dynamic reactions to script availability. ### Event Handlers - **OnScriptLoaded(IScriptReference script)**: Called automatically when any script finishes loading. The `script` parameter provides information about the loaded script. - **OnScriptUnloaded(IScriptReference script)**: Called automatically when any script is unloaded. The `script` parameter provides information about the unloaded script. ### Example Usage ```csharp public class ScriptMonitor : RustScript { // Called automatically when any script finishes loading public void OnScriptLoaded(IScriptReference script) { Debug.Log($"Script loaded: {script.Name}"); if (script.Name == "UtilityScript") { // Perform setup that depends on UtilityScript script.InvokeProcedure("Initialize"); } } // Called automatically when any script is unloaded public void OnScriptUnloaded(IScriptReference script) { Debug.Log($"Script unloaded: {script.Name}"); // Clean up any references or cached data } } ``` ``` -------------------------------- ### Handle Script Loading and Invocation Exceptions (C#) Source: https://context7.com/facepunch/rust.modloader/llms.txt Details the custom exception types provided by the Rust mod loader for script loading (`ScriptLoadException`) and invocation (`ScriptInvocationException`). Includes an example of how to use a try-catch block to gracefully handle potential errors when calling methods on other scripts. ```csharp using Rust.ModLoader.Exceptions; // ScriptLoadException is thrown when script compilation or initialization fails // Contains: ScriptName property identifying which script failed // ScriptInvocationException is thrown when calling functions on scripts fails // Contains: Message describing the failed call // Example script with error handling public class SafeScript : RustScript { private IScriptReference _OtherScript; public void CallOtherScript() { try { // This may throw ScriptInvocationException if OtherScript is not loaded var result = _OtherScript.InvokeFunction("GetData"); Debug.Log($"Got result: {result}"); } catch (ScriptInvocationException ex) { Debug.LogError($"Failed to invoke script: {ex.Message}"); } } } ``` -------------------------------- ### Handle Script Load/Unload Notifications (C#) Source: https://context7.com/facepunch/rust.modloader/llms.txt Shows how scripts can automatically receive notifications when other scripts are loaded or unloaded. This allows for dynamic setup and cleanup of dependencies. The `OnScriptLoaded` and `OnScriptUnloaded` methods are automatically called by the mod loader. ```csharp // Scripts/ScriptMonitor.cs public class ScriptMonitor : RustScript { // Called automatically when any script finishes loading public void OnScriptLoaded(IScriptReference script) { Debug.Log($"Script loaded: {script.Name}"); Debug.Log($"Is loaded: {script.IsLoaded}"); if (script.Name == "UtilityScript") { // Perform setup that depends on UtilityScript script.InvokeProcedure("Initialize"); } } // Called automatically when any script is unloaded public void OnScriptUnloaded(IScriptReference script) { Debug.Log($"Script unloaded: {script.Name}"); // Clean up any references or cached data } } ``` -------------------------------- ### Implement Server Update Hook for Frame-Based Updates (C#) Source: https://context7.com/facepunch/rust.modloader/llms.txt Explains how the mod loader integrates with the Rust server's update loop, allowing scripts to execute code on every server frame. The `Update` method is called automatically, enabling periodic tasks and frame-dependent logic. An example demonstrates counting ticks and performing actions at intervals. ```csharp // Scripts/TickCounter.cs public class TickCounter : RustScript { private int _tickCount = 0; private float _elapsedTime = 0f; // Called every server frame (via ServerMgr.Update hook) public void Update() { _tickCount++; // Perform periodic tasks if (_tickCount % 300 == 0) // Roughly every 5 seconds at 60fps { Debug.Log($"Server has been running for {_tickCount} ticks"); PerformPeriodicTask(); } } private void PerformPeriodicTask() { // Save data, check conditions, etc. Broadcast("OnPeriodicUpdate", _tickCount); } } ``` -------------------------------- ### Create a Basic Rust.ModLoader Script (C#) Source: https://context7.com/facepunch/rust.modloader/llms.txt Demonstrates how to create a basic mod script for Rust.ModLoader. Scripts must inherit from `RustScript` and implement lifecycle methods like `Initialize` and `Dispose`. The filename must match the class name and be placed in the 'Scripts' folder. ```csharp // Scripts/HelloWorld.cs using UnityEngine; public class HelloWorld : RustScript { public override void Initialize() { Debug.Log("HelloWorld script initialized!"); } public override void Dispose() { Debug.Log("HelloWorld script is being unloaded."); } // Called every server frame via the Update hook public void Update() { // Called every server tick } } ``` -------------------------------- ### Subscribe to Rust.ModLoader Script Lifecycle Events (C#) Source: https://context7.com/facepunch/rust.modloader/llms.txt Shows how to subscribe to script loading and unloading events provided by the `ScriptManager`. This allows for custom logic to be executed when scripts are initialized or disposed. ```csharp // Accessing the script manager ScriptManager scripts = ModLoader.Scripts; // Subscribe to lifecycle events scripts.OnScriptLoading += (script) => { Debug.Log($"Script '{script.Name}' is being initialized..."); }; scripts.OnScriptLoaded += (script) => { Debug.Log($"Script '{script.Name}' has been loaded successfully."); }; scripts.OnScriptUnloading += (script) => { Debug.Log($"Script '{script.Name}' is about to be disposed..."); }; scripts.OnScriptUnloaded += (script) => { Debug.Log($"Script '{script.Name}' has been unloaded."); }; ``` -------------------------------- ### Invoke Methods on Scripts using IScriptReference API (C#) Source: https://context7.com/facepunch/rust.modloader/llms.txt Demonstrates how to use the IScriptReference interface to invoke methods (procedures and functions) on other scripts, access their state via reflection, and check their loaded status. This is crucial for inter-script communication within the Rust mod loader. ```csharp public class ScriptCaller : RustScript { private IScriptReference _TargetScript; public void DemonstrateAPI() { // Check if script is loaded if (_TargetScript == null || !_TargetScript.IsLoaded) { Debug.Log("Target script is not available"); return; } // Get script name Debug.Log($"Script name: {_TargetScript.Name}"); // Invoke procedure (void return) _TargetScript.InvokeProcedure("DoSomething"); // Invoke procedure with one argument _TargetScript.InvokeProcedure("ProcessData", "some data"); // Invoke procedure with two arguments _TargetScript.InvokeProcedure("HandleEvent", "click", 42); // Invoke function (with return value) bool isReady = _TargetScript.InvokeFunction("IsReady"); // Invoke function with argument string result = _TargetScript.InvokeFunction("FormatNumber", 100); // Access via reflection (advanced) Type scriptType = _TargetScript.ReflectionType; object scriptInstance = _TargetScript.ReflectionInstance; } } ``` -------------------------------- ### Broadcast Messages Between Scripts in Rust.ModLoader (C#) Source: https://context7.com/facepunch/rust.modloader/llms.txt Illustrates how scripts can communicate with each other using the `Broadcast` method. This method sends a message to all other loaded scripts, which can then handle it if they implement a public method with a matching signature. ```csharp // Scripts/EventEmitter.cs public class EventEmitter : RustScript { public void TriggerEvent() { // Broadcast with no arguments Broadcast("OnCustomEvent"); // Broadcast with one argument Broadcast("OnPlayerJoined", "PlayerName123"); // Broadcast with two arguments Broadcast("OnItemCrafted", "wood", 100); } } // Scripts/EventListener.cs public class EventListener : RustScript { public void OnCustomEvent() { Debug.Log("Custom event received!"); } public void OnPlayerJoined(string playerName) { Debug.Log($"Player joined: {playerName}"); } public void OnItemCrafted(string itemName, int quantity) { Debug.Log($"Crafted {quantity}x {itemName}"); } } ``` -------------------------------- ### Inter-Script References in Rust.ModLoader (C#) Source: https://context7.com/facepunch/rust.modloader/llms.txt Demonstrates how to establish references between scripts using `IScriptReference`. The mod loader automatically injects references to other scripts based on their class names (underscores are trimmed). This allows scripts to call functions and access properties of other loaded scripts. ```csharp // Scripts/UtilityScript.cs public class UtilityScript : RustScript { public int Calculate(int a, int b) { return a + b; } public string GetServerInfo() { return "Rust Server v1.0"; } } // Scripts/MainScript.cs public class MainScript : RustScript { // Auto-populated reference to UtilityScript (matches by name) private IScriptReference _UtilityScript; public override void Initialize() { if (_UtilityScript != null && _UtilityScript.IsLoaded) { // Call a function with return value int result = _UtilityScript.InvokeFunction("Calculate", 5, 10); Debug.Log($"Calculation result: {result}"); // Output: 15 // Call a function with no arguments string info = _UtilityScript.InvokeFunction("GetServerInfo"); Debug.Log($"Server info: {info}"); } } } ``` -------------------------------- ### Exception Handling Source: https://context7.com/facepunch/rust.modloader/llms.txt The mod loader provides custom exceptions for script loading and invocation errors, aiding in robust error management and debugging. ```APIDOC ## Exception Handling ### Description The mod loader provides custom exceptions for script loading and invocation errors, facilitating robust error management. ### Custom Exceptions - **ScriptLoadException**: Thrown when script compilation or initialization fails. Contains a `ScriptName` property identifying the failed script. - **ScriptInvocationException**: Thrown when calling functions or procedures on scripts fails. Contains a `Message` describing the failed call. ### Example Usage ```csharp using Rust.ModLoader.Exceptions; public class SafeScript : RustScript { private IScriptReference _OtherScript; public void CallOtherScript() { try { // This may throw ScriptInvocationException if OtherScript is not loaded var result = _OtherScript.InvokeFunction("GetData"); Debug.Log($"Got result: {result}"); } catch (ScriptInvocationException ex) { Debug.LogError($"Failed to invoke script: {ex.Message}"); } catch (ScriptLoadException ex) // Example for script loading errors { Debug.LogError($"Script loading failed: {ex.ScriptName} - {ex.Message}"); } } } ``` ``` -------------------------------- ### IScriptReference API Source: https://context7.com/facepunch/rust.modloader/llms.txt The IScriptReference interface allows invoking methods and accessing state of other scripts via reflection. It supports invoking procedures and functions with various argument counts and return types. ```APIDOC ## IScriptReference API ### Description Provides methods for invoking methods on other scripts and accessing their state via reflection. ### Methods - **InvokeProcedure(string procedureName, params object[] args)**: Invokes a procedure (void return) on the target script. - **InvokeFunction(string functionName, params object[] args)**: Invokes a function with a specified return type T on the target script. - **InvokeFunction(string functionName, params object[] args)**: Overload for invoking functions with specific argument and return types. ### Properties - **Name** (string): Gets the name of the script. - **IsLoaded** (bool): Checks if the script is currently loaded. - **ReflectionType** (Type): Gets the reflection Type of the script. - **ReflectionInstance** (object): Gets the reflection Instance of the script. ### Example Usage ```csharp // Assuming _TargetScript is an IScriptReference instance // Check if script is loaded if (_TargetScript != null && _TargetScript.IsLoaded) { // Invoke procedure _TargetScript.InvokeProcedure("DoSomething"); // Invoke procedure with arguments _TargetScript.InvokeProcedure("ProcessData", "some data"); _TargetScript.InvokeProcedure("HandleEvent", "click", 42); // Invoke function with return value bool isReady = _TargetScript.InvokeFunction("IsReady"); // Invoke function with arguments and return value string result = _TargetScript.InvokeFunction("FormatNumber", 100); // Access via reflection Type scriptType = _TargetScript.ReflectionType; object scriptInstance = _TargetScript.ReflectionInstance; } ``` ``` -------------------------------- ### Server Update Hook Source: https://context7.com/facepunch/rust.modloader/llms.txt The mod loader integrates with the Rust server's update loop, offering a frame-based update mechanism for scripts to execute logic periodically. ```APIDOC ## Server Update Hook ### Description The mod loader hooks into the Rust server's update loop to provide a frame-based update mechanism for scripts. ### Update Method - **Update()**: Called every server frame. This method is intended for periodic tasks and logic that needs to run continuously. ### Example Usage ```csharp public class TickCounter : RustScript { private int _tickCount = 0; // Called every server frame (via ServerMgr.Update hook) public void Update() { _tickCount++; // Perform periodic tasks if (_tickCount % 300 == 0) // Roughly every 5 seconds at 60fps { Debug.Log($"Server has been running for {_tickCount} ticks"); PerformPeriodicTask(); } } private void PerformPeriodicTask() { // Save data, check conditions, etc. Broadcast("OnPeriodicUpdate", _tickCount); } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.