### UdonSharp Dictionary Example: Key-Value Storage Source: https://context7.com/merlinvr/udonsharp/llms.txt Illustrates the use of UdonSharp's Dictionary for key-value storage. This example shows how to create a dictionary, add key-value pairs using different syntaxes, check for the existence of keys, safely retrieve values, remove entries, and get the total count of items in the dictionary. ```csharp using UnityEngine; using UdonSharp; using UdonSharp.Lib.Internal.Collections; public class DictionaryExample : UdonSharpBehaviour { private void Start() { Dictionary playerNames = new Dictionary(); // Add key-value pairs playerNames.Add(1, "Player1"); playerNames.Add(2, "Player2"); playerNames[3] = "Player3"; // Alternative syntax // Check if key exists if (playerNames.ContainsKey(1)) { Debug.Log($"Player 1: {playerNames[1]}"); } // Try get value safely if (playerNames.TryGetValue(2, out string name)) { Debug.Log($"Found: {name}"); } // Remove key playerNames.Remove(1); // Get count Debug.Log($"Dictionary size: {playerNames.Count}"); } } ``` -------------------------------- ### Player Settings Configuration Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/Examples.md Configures player movement parameters such as jump impulse, walk speed, run speed, and gravity. This script uses `VRCPlayerApi` to modify local player settings. It requires `VRC.SDKBase` and `UdonSharp` namespaces. The `Start` method initializes these settings. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; public class PlayerModSettings : UdonSharpBehaviour { VRCPlayerApi playerApi; [Header("Player Settings")] [SerializeField] float jumpImpulse = 3; [SerializeField] float walkSpeed = 2; [SerializeField] float runSpeed = 4; [SerializeField] float gravityStrengh = 1; void Start() { playerApi = Networking.LocalPlayer; playerApi.SetJumpImpulse(jumpImpulse); playerApi.SetWalkSpeed(walkSpeed); playerApi.SetRunSpeed(runSpeed); playerApi.SetGravityStrength(gravityStrengh); } } ``` -------------------------------- ### Iterate Player List in VRChat with UdonSharp Source: https://context7.com/merlinvr/udonsharp/llms.txt This code shows how to get all players in a VRChat instance, iterate through them, and access their properties. It uses `VRCPlayerApi` to get player data. It also shows examples of `OnPlayerJoined` and `OnPlayerLeft` events. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; public class PlayerListExample : UdonSharpBehaviour { private void Start() { // Get player count int playerCount = VRCPlayerApi.GetPlayerCount(); Debug.Log($"Players in instance: {playerCount}"); // Allocate array and get all players VRCPlayerApi[] players = new VRCPlayerApi[playerCount]; VRCPlayerApi.GetPlayers(players); // Iterate through players foreach (VRCPlayerApi player in players) { if (player != null && player.IsValid()) { Debug.Log($"Player: {player.displayName}, ID: {player.playerId}, IsMaster: {player.isMaster}"); } } } public override void OnPlayerJoined(VRCPlayerApi player) { Debug.Log($"{player.displayName} joined the instance"); } public override void OnPlayerLeft(VRCPlayerApi player) { Debug.Log($"{player.displayName} left the instance"); } } ``` -------------------------------- ### Install Project Dependencies with Yarn Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/README.md Installs the necessary project dependencies using Yarn. This is typically the first step before running other development commands. ```shell yarn ``` -------------------------------- ### Get All Players in Instance Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/Examples.md Demonstrates how to retrieve all players currently in the VRChat instance using `VRCPlayerApi.GetPlayers`. It then iterates through the retrieved player array and logs their display names to the console. Requires `UdonSharp` and `VRC.SDKBase`. ```csharp using UdonSharp; using UnityEngine; using VRC.SDKBase; public class GetPlayersExample : UdonSharpBehaviour { // World capacity is 10, so we create a new array with length of 20 (Hard cap) VRCPlayerApi[] players = new VRCPlayerApi[20]; void Start() { VRCPlayerApi.GetPlayers(players); foreach(VRCPlayerApi player in players) { if(player == null) continue; Debug.Log(player.displayName); } } } ``` -------------------------------- ### Configure Player Locomotion Settings in C# Source: https://context7.com/merlinvr/udonsharp/llms.txt Allows configuration of player locomotion settings such as jump height, run/walk/strafe speeds, and gravity. This C# script uses UdonSharp and VRChat SDK components to modify player movement parameters. It includes an option to enable legacy locomotion. The Start method applies these settings to the local player and then destroys the script instance. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; [UdonBehaviourSyncMode(BehaviourSyncMode.NoVariableSync)] public class PlayerModSetter : UdonSharpBehaviour { public float jumpHeight = 3f; public float runSpeed = 4f; public float walkSpeed = 2f; public float strafeSpeed = 2f; public float gravity = 1f; [Tooltip("Enables legacy locomotion which allows stutter stepping and wall climbing")] public bool useLegacyLocomotion = false; void Start() { var playerApi = Networking.LocalPlayer; // Prevent error in editor from null player API if (playerApi != null) { playerApi.SetJumpImpulse(jumpHeight); playerApi.SetRunSpeed(runSpeed); playerApi.SetWalkSpeed(walkSpeed); playerApi.SetStrafeSpeed(strafeSpeed); playerApi.SetGravityStrength(gravity); if (useLegacyLocomotion) playerApi.UseLegacyLocomotion(); } Destroy(this); } } ``` -------------------------------- ### Start Local Development Server with Yarn Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/README.md Starts a local development server for the website. Changes are reflected live without needing to restart the server, facilitating rapid development. ```shell yarn start ``` -------------------------------- ### UdonSharp Script Communication Example Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/Examples.md An example showcasing communication between two UdonSharp behaviours. It demonstrates accessing public variables and calling methods/events on another `UdonSharpBehaviour` instance, including sending network events to all clients or specific clients. Requires `UdonSharp` and `VRC.SDKBase`. ```csharp using UdonSharp; using UnityEngine; using VRC.SDKBase; using VRC.Udon.Common.Interfaces; namespace UdonSharpExample { public class Example : UdonSharpBehaviour { // UdonSharpBehaviour Class (Affects the Inspector) [SerializeField] AnotherExample anotherExample; void Start() { // Same as: anotherExample.GetProgramVariable("publicBoolean"); if(anotherExample.publicBoolean) { // Same as: anotherExample.SendCustomEvent("RunMethod"); anotherExample.RunMethod(); } } // VRChat Event public override void Interact() { // Same as: SendCustomEvent("DoStuff"); DoStuff(); } public void DoStuff() { // This will be sent to all clients and run locally on each one (including the one sending) SendCustomNetworkEvent(NetworkEventTarget.All, "NetworkEventStuff"); } public void NetworkEventStuff() { // Same as: anotherExample.SetProgramVariable("publicBoolean", false); anotherExample.publicBoolean = false; // Same as: anotherExample.SendCustomEvent("RunMethod"); anotherExample.RunMethod(); anotherExample.SendCustomNetworkEvent(NetworkEventTarget.Owner, "DoOwnerStuff"); } } } ``` -------------------------------- ### Player Tracking and Teleportation in C# Source: https://context7.com/merlinvr/udonsharp/llms.txt Allows retrieving a player's current position and teleporting them to a specified destination. This C# script, using UdonSharp and VRChat SDK, implements an `Interact` method. When the player interacts with the object, it gets the local player's position, logs it, and then teleports the player to the `teleportDestination` transform. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; public class PlayerTeleporter : UdonSharpBehaviour { public Transform teleportDestination; public override void Interact() { VRCPlayerApi player = Networking.LocalPlayer; if (player != null && player.IsValid()) { Vector3 currentPos = player.GetPosition(); Debug.Log($"Player position: {currentPos}"); // Teleport player to destination player.TeleportTo( teleportDestination.position, teleportDestination.rotation, VRC_SceneDescriptor.SpawnOrientation.Default, false // don't lerp on remote ); } } } ``` -------------------------------- ### UdonSharp List Example: Dynamic Array Operations Source: https://context7.com/merlinvr/udonsharp/llms.txt Demonstrates the usage of UdonSharp's generic List for dynamic array operations. This includes creating a list with an initial capacity, adding and accessing elements by index, iterating through the list, removing specific items, and clearing the entire list. ```csharp using UnityEngine; using UdonSharp; using UdonSharp.Lib.Internal.Collections; public class ListExample : UdonSharpBehaviour { private void Start() { // Create list with initial capacity List names = new List(10); // Add items names.Add("Alice"); names.Add("Bob"); names.Add("Charlie"); // Access by index Debug.Log($"First name: {names[0]}"); // Count and iteration Debug.Log($"Total names: {names.Count}"); foreach (string name in names) { Debug.Log($"Name: {name}"); } // Remove item names.Remove("Bob"); // Clear all names.Clear(); } } ``` -------------------------------- ### UdonSharp Utilities Example: Object Validity and Array Shuffling Source: https://context7.com/merlinvr/udonsharp/llms.txt Demonstrates UdonSharp's Utilities class for checking object validity and manipulating arrays. This includes verifying if a player object is still valid after leaving the game and randomly shuffling the elements of an integer array. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; public class UtilitiesExample : UdonSharpBehaviour { public override void OnPlayerLeft(VRCPlayerApi player) { // Check if player object is still valid if (Utilities.IsValid(player)) { Debug.Log($"{player.displayName} is valid"); } else { Debug.Log("Player object is no longer valid after leaving"); } } private void Start() { // Shuffle array randomly int[] numbers = new int[] { 1, 2, 3, 4, 5 }; Utilities.ShuffleArray(numbers); foreach (int num in numbers) { Debug.Log($"Shuffled number: {num}"); } } } ``` -------------------------------- ### Recursive Factorial Calculation in C# Source: https://context7.com/merlinvr/udonsharp/llms.txt Calculates the factorial of a number using recursion. This C# script utilizes the [RecursiveMethod] attribute, which is specific to UdonSharp for handling recursive calls within the Udon environment. It takes an integer 'n' as input and returns its factorial. The example includes a Start method to demonstrate its usage by logging the factorial of 5. ```csharp using UnityEngine; using UdonSharp; public class RecursiveExample : UdonSharpBehaviour { [RecursiveMethod] public int Factorial(int n) { if (n <= 1) return 1; return n * Factorial(n - 1); } private void Start() { Debug.Log($"Factorial of 5 is {Factorial(5)}"); // Output: 120 } } ``` -------------------------------- ### Dynamic Variable Access in C# Source: https://context7.com/merlinvr/udonsharp/llms.txt Enables getting and setting Udon program variables by their string names at runtime. This C# script provides methods `ModifyVariables` which uses `GetProgramVariable` to retrieve a variable's value and `SetProgramVariable` to update it. It demonstrates accessing and modifying public variables like 'health' and 'playerName'. ```csharp using UnityEngine; using UdonSharp; public class DynamicAccessExample : UdonSharpBehaviour { public int health = 100; public string playerName = "Player1"; public void ModifyVariables() { // Get variable by name object currentHealth = GetProgramVariable("health"); Debug.Log($"Current health: {currentHealth}"); // Set variable by name SetProgramVariable("health", 75); SetProgramVariable("playerName", "Player2"); Debug.Log($"New health: {health}, New name: {playerName}"); } } ``` -------------------------------- ### Instantiate Objects Locally in VRChat with UdonSharp Source: https://context7.com/merlinvr/udonsharp/llms.txt This code demonstrates how to instantiate objects locally (non-networked) in VRChat using UdonSharp. It uses `VRCInstantiate` to create a copy of a prefab. The spawned object's position and rotation are set according to a specified spawn point. Useful for visual effects and local interactions. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; public class ObjectSpawner : UdonSharpBehaviour { public GameObject prefab; public Transform spawnPoint; public override void Interact() { // VRCInstantiate creates a local, non-synced copy GameObject spawnedObject = VRC.SDKBase.VRCInstantiate(prefab); if (spawnedObject != null) { spawnedObject.transform.position = spawnPoint.position; spawnedObject.transform.rotation = spawnPoint.rotation; Debug.Log("Object spawned locally"); } } } ``` -------------------------------- ### Get Synchronized Server Time and Delta Time in UdonSharp Source: https://context7.com/merlinvr/udonsharp/llms.txt This snippet shows how to retrieve the synchronized server time in seconds, milliseconds, and as a DateTime object using VRChat's Networking API. It also demonstrates calculating the time difference between two server time readings. This is useful for time-sensitive game logic and synchronization in multiplayer environments. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; using System; public class ServerTimeExample : UdonSharpBehaviour { private double previousTime; private void Start() { // Get current server time in seconds double currentTime = Networking.GetServerTimeInSeconds(); Debug.Log($"Server time (seconds): {currentTime}"); // Get server time in milliseconds int timeMs = Networking.GetServerTimeInMilliseconds(); Debug.Log($"Server time (ms): {timeMs}"); // Get network DateTime DateTime networkTime = Networking.GetNetworkDateTime(); Debug.Log($"Network DateTime: {networkTime}"); previousTime = currentTime; } private void Update() { double currentTime = Networking.GetServerTimeInSeconds(); // Calculate delta time using server time double deltaTime = Networking.CalculateServerDeltaTime(currentTime, previousTime); previousTime = currentTime; } } ``` -------------------------------- ### Player Teleportation Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/Examples.md Allows a player to teleport to a specified target position and rotation when interacting with the GameObject. It uses `Networking.LocalPlayer.TeleportTo` and requires a `Transform` variable for the destination. Dependencies include `UdonSharp` and `VRC.SDKBase`. ```csharp using UdonSharp; using UnityEngine; using VRC.SDKBase; public class TeleportPlayer : UdonSharpBehaviour { [SerializeField] Transform targetPosition; public override void Interact() { Networking.LocalPlayer.TeleportTo(targetPosition.position, targetPosition.rotation, VRC_SceneDescriptor.SpawnOrientation.Default, false); } } ``` -------------------------------- ### Example Custom Inspector for UdonSharpBehaviour in Unity Source: https://github.com/merlinvr/udonsharp/wiki/Editor-Scripting This complete C# example defines a UdonSharpBehaviour with a custom inspector. It includes necessary `using` statements, preprocessor directives for editor-only code, and implements `OnInspectorGUI` to draw default UdonSharp headers and a custom string field with undo handling. ```csharp using UnityEngine; using VRC.SDK3.Components; using VRC.SDKBase; using VRC.Udon; #if !COMPILER_UDONSHARP && UNITY_EDITOR // These using statements must be wrapped in this check to prevent issues on builds using UnityEditor; using UdonSharpEditor; #endif namespace UdonSharp.Examples.Inspectors { /// /// Example behaviour that has a custom inspector /// public class CustomInspectorBehaviour : UdonSharpBehaviour { public string stringVal; private void Update() { Debug.Log($"CustomInspectorBehaviour: {stringVal}"); } } // Editor scripts must be wrapped in a UNITY_EDITOR check to prevent issues while uploading worlds. The !COMPILER_UDONSHARP check prevents UdonSharp from throwing errors about unsupported code here. #if !COMPILER_UDONSHARP && UNITY_EDITOR [CustomEditor(typeof(CustomInspectorBehaviour))] public class CustomInspectorEditor : Editor { public override void OnInspectorGUI() { // Draws the default convert to UdonBehaviour button, program asset field, sync settings, etc. if (UdonSharpGUI.DrawDefaultUdonSharpBehaviourHeader(target)) return; CustomInspectorBehaviour inspectorBehaviour = (CustomInspectorBehaviour)target; EditorGUI.BeginChangeCheck(); // A simple string field modification with Undo handling string newStrVal = EditorGUILayout.TextField("String Val", inspectorBehaviour.stringVal); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(inspectorBehaviour, "Modify string val"); inspectorBehaviour.stringVal = newStrVal; } } } #endif } ``` -------------------------------- ### Synchronize Network Variables with Interpolation in UdonSharp Source: https://context7.com/merlinvr/udonsharp/llms.txt This example shows how to synchronize variables across the network with different interpolation modes using UdonSharp. It utilizes the `UdonSynced` attribute with various `UdonSyncMode` options to achieve smooth networked behavior. The code updates a networked position based on ownership. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; [UdonBehaviourSyncMode(BehaviourSyncMode.Continuous)] public class InterpolationExample : UdonSharpBehaviour { // No interpolation (default) [UdonSynced] public int score; // Linear interpolation for smooth values [UdonSynced(UdonSyncMode.Linear)] public float health; // Smooth interpolation for positions/rotations [UdonSynced(UdonSyncMode.Smooth)] public Vector3 position; private void Update() { if (Networking.IsOwner(gameObject)) { // Owner updates values, they sync automatically with Continuous mode position = transform.position; } else { // Non-owners read interpolated values transform.position = position; } } } ``` -------------------------------- ### Implement Master-Only Control with UdonSharp Source: https://context7.com/merlinvr/udonsharp/llms.txt This script allows only the instance master to control a GameObject's state, which is then synced to all players. It uses UdonSharpBehaviour, UdonSynced, and VRC.SDKBase. The OnOwnershipRequest method prevents non-masters from taking ownership. The Interact method only executes if the player is the master. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; [UdonBehaviourSyncMode(BehaviourSyncMode.Manual)] public class MasterToggleObject : UdonSharpBehaviour { public GameObject toggleObject; [UdonSynced] bool isObjectEnabled; private void Start() { isObjectEnabled = toggleObject.activeSelf; } // Prevents people who are not the master from taking ownership public override bool OnOwnershipRequest(VRCPlayerApi requestingPlayer, VRCPlayerApi requestedOwner) { return requestedOwner.isMaster; } public override void OnDeserialization() { toggleObject.SetActive(isObjectEnabled); } public override void Interact() { if (!Networking.IsMaster) return; else if (!Networking.IsOwner(gameObject)) Networking.SetOwner(Networking.LocalPlayer, gameObject); isObjectEnabled = !isObjectEnabled; toggleObject.SetActive(isObjectEnabled); RequestSerialization(); } } ``` -------------------------------- ### Control VRC Stations Using UdonSharp Source: https://context7.com/merlinvr/udonsharp/llms.txt This code snippet demonstrates how to control VRC Stations using UdonSharp, including configuring station behavior and handling player entry and exit events. It allows for customizing station settings such as player mobility and interaction options. This is useful for creating interactive seating or control points in VRChat worlds. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; using VRC.SDK3.Components; public class StationController : UdonSharpBehaviour { public VRCStation station; private void Start() { // Configure station station.PlayerMobility = VRCStation.Mobility.Immobilize; station.canUseStationFromStation = false; station.disableStationExit = false; } public override void Interact() { VRCPlayerApi player = Networking.LocalPlayer; station.UseStation(player); } public override void OnStationEntered(VRCPlayerApi player) { Debug.Log($"{player.displayName} sat down"); } public override void OnStationExited(VRCPlayerApi player) { Debug.Log($"{player.displayName} stood up"); } } ``` -------------------------------- ### Network Ownership Management in C# Source: https://context7.com/merlinvr/udonsharp/llms.txt Facilitates checking and transferring network ownership of game objects. This C# script uses UdonSharp and VRChat SDK to determine if the local player is the instance master (`Networking.IsMaster`), if they own a specific object (`Networking.IsOwner`), and to retrieve the current owner (`Networking.GetOwner`). The `Interact` method allows the local player to take ownership if they don't already have it. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; public class OwnershipExample : UdonSharpBehaviour { private void Start() { // Check if local player is master if (Networking.IsMaster) { Debug.Log("I am the instance master!"); } // Check if local player owns this object if (Networking.IsOwner(gameObject)) { Debug.Log("I own this object"); } // Get current owner VRCPlayerApi owner = Networking.GetOwner(gameObject); Debug.Log($"Owner: {owner.displayName}"); } public override void Interact() { // Take ownership when interacting if (!Networking.IsOwner(gameObject)) { Networking.SetOwner(Networking.LocalPlayer, gameObject); Debug.Log("Took ownership of object"); } } } ``` -------------------------------- ### Spinning Cube Rotation Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/Examples.md A simple Unity script using UdonSharp to continuously rotate a GameObject around the Y-axis. It utilizes the `Update` method for continuous rotation and `Time.deltaTime` for frame-rate independence. No external dependencies are required beyond Unity's `Transform` component. ```csharp using UnityEngine; using UdonSharp; public class RotatingCubeBehaviour : UdonSharpBehaviour { private void Update() { transform.Rotate(Vector3.up, 90f * Time.deltaTime); } } ``` -------------------------------- ### Send Network Events with Parameters in C# Source: https://context7.com/merlinvr/udonsharp/llms.txt Demonstrates sending custom network events with up to 8 parameters using UdonSharp. This C# script defines a method `SendScoreUpdate` that triggers a network event `OnScoreUpdated` sent to all clients. The `[NetworkCallable]` attribute marks the event handler. This is useful for synchronizing game state or actions across players. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; using VRC.Udon.Common.Interfaces; public class NetworkEventExample : UdonSharpBehaviour { public void SendScoreUpdate(int playerId, int score) { SendCustomNetworkEvent(NetworkEventTarget.All, nameof(OnScoreUpdated), playerId, score); } [NetworkCallable] public void OnScoreUpdated(int playerId, int score) { Debug.Log($"Player {playerId} scored {score} points!"); } } ``` -------------------------------- ### Toggle Objects Interactively with UdonSharp Source: https://context7.com/merlinvr/udonsharp/llms.txt This script toggles the active state of GameObjects when a player interacts with it. It uses UdonSharpBehaviour and an array of GameObjects. The Interact method iterates through the array and toggles each object's active state. ```csharp using UnityEngine; using UdonSharp; [UdonBehaviourSyncMode(BehaviourSyncMode.NoVariableSync)] public class InteractToggle : UdonSharpBehaviour { [Tooltip("List of objects to toggle on and off")] public GameObject[] toggleObjects; public override void Interact() { foreach (GameObject toggleObject in toggleObjects) { if (toggleObject != null) { toggleObject.SetActive(!toggleObject.activeSelf); } } } } ``` -------------------------------- ### Rotate Object with UdonSharp Source: https://context7.com/merlinvr/udonsharp/llms.txt This script rotates a GameObject using UdonSharp. It inherits from UdonSharpBehaviour and updates the object's rotation in the Update method, rotating it around the up vector by 90 degrees per second. ```csharp using UnityEngine; using UdonSharp; public class RotatingCube : UdonSharpBehaviour { private void Update() { transform.Rotate(Vector3.up, 90f * Time.deltaTime); } } ``` -------------------------------- ### UdonSharp - Video Player Events Source: https://github.com/merlinvr/udonsharp/wiki/Events A set of events related to the VRChat video player. These cover the entire lifecycle of video playback, including starting, pausing, ending, errors, and when the video is ready to play. ```csharp public override void OnVideoEnd() {} ``` ```csharp public override void OnVideoError(VideoError videoError) {} ``` ```csharp public override void OnVideoLoop() {} ``` ```csharp public override void OnVideoPause() {} ``` ```csharp public override void OnVideoPlay() {} ``` ```csharp public override void OnVideoStart() {} ``` ```csharp public override void OnVideoReady() {} ``` -------------------------------- ### Sync Variable Globally with UdonSharp Source: https://context7.com/merlinvr/udonsharp/llms.txt This script synchronizes a boolean variable across all clients to toggle a GameObject's active state. It uses UdonSharpBehaviour, UdonSynced, and VRC.SDKBase. The Interact method toggles the isEnabled variable, sets the GameObject's active state, and requests serialization. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; [UdonBehaviourSyncMode(BehaviourSyncMode.Manual)] public class GlobalToggleObject : UdonSharpBehaviour { public GameObject toggleObject; [UdonSynced] bool isEnabled; private void Start() { isEnabled = toggleObject.activeSelf; } public override void OnDeserialization() { if (!Networking.IsOwner(gameObject)) toggleObject.SetActive(isEnabled); } public override void Interact() { if (!Networking.IsOwner(gameObject)) Networking.SetOwner(Networking.LocalPlayer, gameObject); isEnabled = !isEnabled; toggleObject.SetActive(isEnabled); RequestSerialization(); } } ``` -------------------------------- ### Trigger Field Change Callback with UdonSharp Source: https://context7.com/merlinvr/udonsharp/llms.txt This script demonstrates how to trigger a callback function when a synced variable changes. It uses UdonSharpBehaviour, UdonSynced, and FieldChangeCallback. The SyncedToggle property setter is called whenever the _syncedToggle variable changes, either through network synchronization or local modification. ```csharp using UnityEngine; using UdonSharp; using VRC.SDKBase; [UdonBehaviourSyncMode(BehaviourSyncMode.Manual)] public class CallbackExample : UdonSharpBehaviour { public GameObject targetObject; [UdonSynced, FieldChangeCallback(nameof(SyncedToggle))] private bool _syncedToggle; public bool SyncedToggle { set { Debug.Log($"Value changed from {_syncedToggle} to {value}"); _syncedToggle = value; targetObject.SetActive(value); } get => _syncedToggle; } public override void Interact() { Networking.SetOwner(Networking.LocalPlayer, gameObject); SyncedToggle = !SyncedToggle; RequestSerialization(); } } ``` -------------------------------- ### Deploy Website with Yarn (SSH) Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/README.md Deploys the website using SSH. This command builds the static content and pushes it to the 'gh-pages' branch, suitable for hosting services like GitHub Pages. ```shell USE_SSH=true yarn deploy ``` -------------------------------- ### Build Static Website Content with Yarn Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/README.md Generates the static content for the website, typically placed in a 'build' directory. This content can then be served by any static hosting service. ```shell yarn build ``` -------------------------------- ### DefaultExecutionOrder Attribute Example in C# Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/UdonSharp.md Shows how to apply the [DefaultExecutionOrder] attribute to control the execution order of UdonSharp behaviours. This example sets the order to 0, affecting when Update, LateUpdate, and FixedUpdate are called relative to other behaviours. ```cs [DefaultExecutionOrder(0)] public class Example : UdonSharpBehaviour { } ``` -------------------------------- ### VRCInstantiate Method Source: https://github.com/merlinvr/udonsharp/wiki/VRChat-API Allows for the instantiation of a GameObject. This method creates a local, non-synced copy of the provided object. ```APIDOC ## VRCInstantiate ### Description Creates a local, non-synced copy of an object. ### Method Static ### Endpoint N/A (Method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp GameObject newObject = VRCInstantiate(originalGameObject); ``` ### Response #### Success Response (200) Type: GameObject Description: A new, non-synced instance of the original GameObject. #### Response Example ```json { "GameObject": "newly_instantiated_object" } ``` ``` -------------------------------- ### UdonBehaviourSyncMode Attribute Example in C# Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/UdonSharp.md Illustrates the use of the [UdonBehaviourSyncMode] attribute to enforce a specific synchronization mode for a UdonSharp behaviour. The example sets the mode to Manual. This attribute helps manage network traffic and data consistency. ```cs [UdonBehaviourSyncMode(BehaviourSyncMode.Manual)] public class Example : UdonSharpBehaviour { } ``` -------------------------------- ### VRCPortalMarker API Source: https://github.com/merlinvr/udonsharp/wiki/VRChat-API Documentation for the VRCPortalMarker component, used to create portals to other rooms. ```APIDOC ## VRCPortalMarker API ### Description A component used to create portals to other rooms. ### Properties - **roomId** (string) - Room Id of the destination room. ### Methods - **RefreshPortal()** - Refreshes the portal displayed to the player. ``` -------------------------------- ### RecursiveMethod Attribute Example in C# Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/UdonSharp.md Demonstrates the [RecursiveMethod] attribute, which allows a method to be called recursively without issues. The example implements a factorial function, highlighting the safe recursive call. Use this attribute only when recursion is necessary due to potential performance overhead. ```cs [RecursiveMethod] int Factorial(int input) { if (input == 1) return 1; return input * Factorial(input - 1); } ``` -------------------------------- ### VRCPickup Component Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/VRChat-API.md API documentation for the VRCPickup component, used for creating pickable objects. ```APIDOC ## VRCPickup Component API ### Description A component used to allow objects to be picked up and held. ### Class `VRC.SDK3.Components.VRCPickup` / `VRC.SDKBase.VRC_Pickup` ### Properties - **MomentumTransferMethod** (ForceMode) - This defines how the collision force will be added to the other object which was hit, using `Rigidbody.AddForceAtPosition`. Note that the force will only be added if `AllowCollisionTransfer` is on. - **DisallowTheft** (bool) - If other users are allowed to take the pickup out of some else's grip. - **ExactGun** (Transform) - The position object will be held if set to Exact Gun. - **ExactGrip** (Transform) - The position object will be held if set to Exact Grip. - **allowManipulationWhenEquipped** (bool) - Should the user be able to manipulate the pickup while the pickup is held if using a controller. - **orientation** (PickupOrientation) - What way the object will be held. - **AutoHold** (AutoHoldMode) - Should the pickup remain in the users hand after they let go of the grab button. - **InteractionText** (string) - Tooltip text that is displayed when holding the pickup. - **UseText** (string) - Tooltip text that is displayed when hovering over the pickup. - **ThrowVelocityBoostMinSpeed** (float) - How fast the object needs to move to be thrown. - **ThrowVelocityBoostScale** (float) - How much throwing should scale, higher = faster thrown while lower means slower throw speed. - **pickupable** (bool) - Determines whether you can pickup the object. - **proximity** (float) - The maximum distance a player can be away from a pickup to interact with it. - **currentPlayer** (VRCPlayerApi) - The player that is currently holding the pickup. - **IsHeld** (bool) - Determines whether the pickup is currently being held by a player. - **currentHand** (PickupHand) - The hand that the player is holding the pickup with. ### Methods - **Drop()** - Drops the pickup if it is being held by a player. - **Drop(VRCPlayerApi instigator)** - Drops the pickup if it is being held by a player. Note that the pickup will only drop if `instigator` is the player who is holding the pickup. - **GenerateHapticEvent(float duration, float amplitude, float frequency)** - Plays haptic feedback on the player's controller. Default values are duration: 0.25, amplitude: 0.5, frequency: 0.5. - **PlayHaptics()** - Plays haptic feedback on the player's controller. ``` -------------------------------- ### VRCPickup API Source: https://github.com/merlinvr/udonsharp/wiki/VRChat-API Documentation for the VRCPickup component, used to enable objects to be picked up and held. ```APIDOC ## VRCPickup API ### Description A component used to allow objects to be picked up and held. ### Properties - **MomentumTransferMethod** (ForceMode) - Defines how the collision force will be added to the other object which was hit, using `Rigidbody.AddForceAtPosition`. Note that the force will only be added if `AllowCollisionTransfer` is on. - **DisallowTheft** (bool) - If other users are allowed to take the pickup out of some else's grip. - **ExactGun** (Transform) - The position object will be held if set to Exact Gun. - **ExactGrip** (Transform) - The position object will be held if set to Exact Grip. - **allowManipulationWhenEquipped** (bool) - Should the user be able to manipulate the pickup while the pickup is held if using a controller. - **orientation** (PickupOrientation) - What way the object will be held. - **AutoHold** (AutoHoldMode) - Should the pickup remain in the users hand after they let go of the grab button. - **InteractionText** (string) - Tooltip text that is displayed when holding the pickup. - **UseText** (string) - Tooltip text that is displayed when hovering over the pickup. - **ThrowVelocityBoostMinSpeed** (float) - How fast the object needs to move to be thrown. - **ThrowVelocityBoostScale** (float) - How much throwing should scale, higher = faster thrown while lower means slower throw speed. - **pickupable** (bool) - Determines whether you can pickup the object. - **proximity** (float) - The maximum distance a player can be away from a pickup to interact with it. - **currentPlayer** (VRCPlayerApi) - The player that is currently holding the pickup. - **IsHeld** (bool) - Determines whether the pickup is currently being held by a player. - **currentHand** (PickupHand) - The hand that the player is holding the pickup with. ### Methods - **Drop()** - Drops the pickup if it is being held by a player. - **Drop(VRCPlayerApi instigator)** - Drops the pickup if it is being held by a player. Note that the pickup will only drop if `instigator` is the player who is holding the pickup. - **GenerateHapticEvent(float duration, float amplitude, float frequency)** - Plays haptic feedback on the player's controller. Default values are duration: 0.25, amplitude: 0.5, frequency: 0.5. - **PlayHaptics()** - Plays haptic feedback on the player's controller. ``` -------------------------------- ### FieldChangeCallback Attribute Example in C# Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/UdonSharp.md Explains the [FieldChangeCallback] attribute, which allows for custom handling of Udon variable changes. This attribute specifies a property name that will be called when the attributed field is modified via network sync or SetProgramVariable. The example assumes a corresponding property exists to handle the field update. ```cs // Example usage would involve a field and a property: // [FieldChangeCallback("MyProperty")] // public int MyField; // // public int MyProperty // { // set // { // MyField = value; // // Additional logic here // } // } ``` -------------------------------- ### Deploy Website with Yarn (No SSH) Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/README.md Deploys the website without using SSH, requiring the GitHub username. This command builds the static content and pushes it to the 'gh-pages' branch. ```shell GIT_USER= yarn deploy ``` -------------------------------- ### VRCPortalMarker Component Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/VRChat-API.md API documentation for the VRCPortalMarker component, used for creating portals to other rooms. ```APIDOC ## VRCPortalMarker Component API ### Description A component used to create portals to other rooms. ### Class `VRC.SDK3.Components.VRCPortalMarker` / `VRC.SDKBase.VRC_PortalMarker` ### Properties - **roomId** (string) - Room Id of the destination room. ### Methods - **RefreshPortal()** - Refreshes the portal displayed to the player. ``` -------------------------------- ### Player Tagging API Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/VRChat-API.md Enables setting, getting, and clearing custom tags associated with players. ```APIDOC ## Player Tagging API ### Description Enables setting, getting, and clearing custom tags associated with players. Note that player tags are not synchronized to remote clients. ### Methods #### SetPlayerTag(string tagName, string tagValue) * **Description**: Assigns a value to the tag for the player. Returns null if the tag has not been assigned. * **Parameters**: * `tagName` (string) - The name of the tag. * `tagValue` (string) - The value to assign to the tag. * **Returns**: `void` #### GetPlayerTag(string tagName) * **Description**: Returns the value of the given tag for the player. Assign a value of null to clear the tag. * **Parameters**: * `tagName` (string) - The name of the tag to retrieve. * **Returns**: `string` #### ClearPlayerTags() * **Description**: Clears the tags on the given player. * **Returns**: `void` ``` -------------------------------- ### Network Time Functions Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/VRChat-API.md Provides methods to get the current server time and calculate time differences. ```APIDOC ## Static Methods for Network Time ### GetNetworkDateTime - **Description**: Retrieves the current network date and time. - **Method**: N/A (Static Method) - **Endpoint**: N/A - **Parameters**: None - **Request Example**: None - **Response**: - **Success Response (200)**: `DateTime` - The current server date and time. - **Response Example**: `"2023-10-27T10:00:00Z"` ### GetServerTimeInSeconds - **Description**: Returns the current server time in seconds. - **Method**: N/A (Static Method) - **Endpoint**: N/A - **Parameters**: None - **Request Example**: None - **Response**: - **Success Response (200)**: `double` - The current server time in seconds. - **Response Example**: `1698381600.500` ### GetServerTimeInMilliseconds - **Description**: Returns the current server time in milliseconds. - **Method**: N/A (Static Method) - **Endpoint**: N/A - **Parameters**: None - **Request Example**: None - **Response**: - **Success Response (200)**: `int` - The current server time in milliseconds. - **Response Example**: `1698381600500` ### CalculateServerDeltaTime - **Description**: Calculates the time difference between two server timestamps. - **Method**: N/A (Static Method) - **Endpoint**: N/A - **Parameters**: - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: None - **Request Example**: None - **Response**: - **Success Response (200)**: `double` - The time difference in seconds. - **Response Example**: `15.250` ``` -------------------------------- ### Get Unique GameObject Name in UdonSharp Source: https://github.com/merlinvr/udonsharp/wiki/VRChat-API This static method returns a unique name for the given GameObject. This can be useful for identification and debugging purposes in networked environments. ```csharp public static string GetUniqueName(GameObject obj) ``` -------------------------------- ### Get UdonSharpBehaviour Components Source: https://github.com/merlinvr/udonsharp/wiki/Editor-Scripting Retrieves UdonSharpBehaviour components from a GameObject using extension methods. `GetUdonSharpComponent()` is the equivalent of `GetComponent()` for UdonSharp, and `GetUdonSharpComponentsInChildren()` finds components on children. ```csharp GameObject sourceGameObject = ... // Get some game object from somewhere here MyComponentType[] myComponents = sourceGameObject.GetUdonSharpComponentsInChildren(); ``` -------------------------------- ### VRCInstantiate Method Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/VRChat-API.md This method creates a local, non-synced copy of a GameObject. It is a static method and returns a GameObject. ```APIDOC ## VRCInstantiate Method ### Description Creates a local, non-synced copy of an object. See [here](https://docs.unity3d.com/ScriptReference/Object.Instantiate.html) for more information. ### Method Static ### Endpoint N/A (Method Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **GameObject** (GameObject) - The instantiated GameObject. #### Response Example None ``` -------------------------------- ### Program Variable Management with UdonBehaviour in UdonSharp Source: https://github.com/merlinvr/udonsharp/wiki/VRChat-API These methods enable you to get and set program variables within a UdonBehaviour. This allows for dynamic modification and retrieval of script data at runtime. ```csharp public object GetProgramVariable(string symbolName) public void SetProgramVariable(string symbolName, object value) public Type GetProgramVariableType(string symbolName) ``` -------------------------------- ### Default Udon Sharp Script Template (C#) Source: https://github.com/merlinvr/udonsharp/blob/master/Tools/Docusaurus/docs/Configuration.md The default template used when creating new Udon Sharp scripts. It includes necessary namespaces and a basic UdonSharpBehaviour structure. The `` placeholder is replaced with the file name when a new script is generated. ```csharp using UdonSharp; using UnityEngine; using VRC.SDKBase; using VRC.Udon; public class : UdonSharpBehaviour { void Start() { } } ``` -------------------------------- ### Get Server Time Information in UdonSharp Source: https://github.com/merlinvr/udonsharp/wiki/VRChat-API These methods provide access to the server's current time, either as a DateTime object, in seconds, or in milliseconds. This is crucial for time-sensitive operations and synchronization. ```csharp public static System.DateTime GetNetworkDateTime() public static double GetServerTimeInSeconds() public static int GetServerTimeInMilliseconds() ```