### Server-Only Connection Approval Example Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/migratingfromUNet.html This server-only example demonstrates setting up the ConnectionApprovalCallback and starting the host. It includes logic for approving connections and specifying a player prefab. ```csharp using Unity.Netcode; private void Setup() { NetworkManager.Singleton.ConnectionApprovalCallback += ApprovalCheck; NetworkManager.Singleton.StartHost(); } private void ApprovalCheck(byte[] connectionData, ulong clientId, NetworkManager.ConnectionApprovedDelegate callback) { //Your logic here bool approve = true; bool createPlayerObject = true; // The Prefab hash. Use null to use the default player prefab // If using this hash, replace "MyPrefabHashGenerator" with the name of a Prefab added to the NetworkPrefabs field of your NetworkManager object in the scene ulong? prefabHash = NetworkpawnManager.GetPrefabHashFromGenerator("MyPrefabHashGenerator"); //If approve is true, the connection gets added. If it's false. The client gets disconnected callback(createPlayerObject, prefabHash, approve, positionToSpawnAt, rotationToSpawnWith); } ``` -------------------------------- ### OnInlineSetup Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Called before creating and starting the server and clients. Override this for inline setup logic. ```csharp protected virtual void OnInlineSetup() ``` -------------------------------- ### OnSetup Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Called before creating and starting the server and clients. Override for setup logic in AllTests and PerTest modes. Returns an IEnumerator. ```csharp protected virtual IEnumerator OnSetup() ``` -------------------------------- ### Server-Side Connection Approval Example Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/basics/connection-approval Implement a callback to handle connection approval requests. This example shows how to set the callback and start the host, then defines the approval logic within the callback. ```csharp using Unity.Netcode; private void Setup() { NetworkManager.Singleton.ConnectionApprovalCallback = ApprovalCheck; NetworkManager.Singleton.StartHost(); } private void ApprovalCheck(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response) { // The client identifier to be authenticated var clientId = request.ClientNetworkId; // Additional connection data defined by user code var connectionData = request.Payload; // Your approval logic determines the following values response.Approved = true; response.CreatePlayerObject = true; // The Prefab hash value of the NetworkPrefab, if null the default NetworkManager player Prefab is used response.PlayerPrefabHash = null; // Position to spawn the player object (if null it uses default of Vector3.zero) response.Position = Vector3.zero; // Rotation to spawn the player object (if null it uses the default of Quaternion.identity) response.Rotation = Quaternion.identity; // If response.Approved is false, you can provide a message that explains the reason why via ConnectionApprovalResponse.Reason // On the client-side, NetworkManager.DisconnectReason will be populated with this message via DisconnectReasonMessage response.Reason = "Some reason for not approving the client"; // If additional approval steps are needed, set this to true until the additional steps are complete // once it transitions from true to false the connection approval response will be processed. response.Pending = false; } ``` -------------------------------- ### Start Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTestHelpers.html Starts NetworkManager instances created by the Create method. This method can configure a host or server and clients, with an optional callback for pre-client start actions. ```APIDOC ## Start(bool, NetworkManager, NetworkManager[], BeforeClientStartCallback, bool) ### Description Starts NetworkManager instances created by the Create method. This method can configure a host or server and clients, with an optional callback for pre-client start actions. ### Method ``` public static bool Start(bool host, NetworkManager server, NetworkManager[] clients, NetcodeIntegrationTestHelpers.BeforeClientStartCallback callback = null, bool startServer = true) ``` ### Parameters #### Path Parameters - **host** (bool) - Required - Whether or not to create a Host instead of Server. - **server** (NetworkManager) - Required - The Server NetworkManager. - **clients** (NetworkManager[]) - Required - The Clients NetworkManager. - **callback** (NetcodeIntegrationTestHelpers.BeforeClientStartCallback) - Optional - Called immediately after the server is started and before client(s) are started. - **startServer** (bool) - Optional - true to start the server, false to not start it. ``` -------------------------------- ### Example Windows Single Command Line with Log Files Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/tutorials/command-line-helper An example of launching both a server and a client on Windows from a single command line, with logs redirected to separate files. Adjust paths and filenames as needed. ```bash C:\Users\sarao>HelloWorld\Build\HelloWorld.exe -logfile log-server.txt -mode server & HelloWorld\Build\HelloWorld.exe -logfile log-client.txt -mode client ``` -------------------------------- ### Start Server Listening Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkTransport.html Starts the server to listen for incoming client connections. Returns true if the server started successfully, false otherwise. ```csharp public abstract bool StartServer() ``` -------------------------------- ### StartServer Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.Transports.UTP.UnityTransport.html Starts listening for incoming clients. Returns false if the server is already started or if port binding fails. ```APIDOC ## StartServer() ### Description Starts to listening for incoming clients Note: When this method returns false it could mean: * You are trying to start a client that is already started * It failed during the initial port binding when attempting to begin to connect ### Method public override bool StartServer() ### Returns - **bool** - true if the server was started and false if it failed to start the server ### Overrides NetworkTransport.StartServer() ``` -------------------------------- ### StartServer() Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.Transports.SinglePlayer.SinglePlayerTransport.html Starts listening for incoming clients. ```APIDOC ## Method: StartServer() ### Description Starts to listening for incoming clients. ### Declaration ```csharp public override bool StartServer() ``` ### Returns - **Type**: bool - **Description**: Returns success or failure. ### Overrides NetworkTransport.StartServer() ``` -------------------------------- ### SetUp Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.IntegrationTestWithApproximation.html Performs setup operations for integration tests. This method is typically called before each test case. ```APIDOC ## SetUp ### Description Performs setup operations for integration tests. This method is typically called before each test case. ### Method `SetUp()` ``` -------------------------------- ### StartHost Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Starts a Host. Returns true if NetworkManager started in host mode successfully. ```APIDOC ## StartHost() ### Description Starts a Host. ### Method public bool StartHost() ### Returns - **bool** - (true/false) returns true if NetworkManager started in host mode successfully. ``` -------------------------------- ### StartClient Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Starts a client. Returns true if NetworkManager started in client mode successfully. ```APIDOC ## StartClient() ### Description Starts a client. ### Method public bool StartClient() ### Returns - **bool** - (true/false) returns true if NetworkManager started in client mode successfully. ``` -------------------------------- ### OnStart Method Override Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.TimeoutFrameCountHelper.html Overrides the base TimeoutHelper.OnStart method. This virtual method is intended for setup logic when the helper is started. ```csharp protected override void OnStart() ``` -------------------------------- ### Replace NetworkServer.Spawn with NetworkObject.Spawn (UNet Example) Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/migratingfromUNet.html This example demonstrates the UNet approach to spawning a GameObject by instantiating it and then calling NetworkServer.Spawn. ```csharp using UnityEngine; using UnityEngine.Networking; public class Example : NetworkBehaviour { //Assign the Prefab in the Inspector public GameObject m_MyGameObject; GameObject m_MyInstantiated; void Start() { //Instantiate the prefab m_MyInstantiated = Instantiate(m_MyGameObject); //Spawn the GameObject you assign in the Inspector NetworkServer.Spawn(m_MyInstantiated); } } ``` -------------------------------- ### StartServer Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Starts a server. Returns true if NetworkManager started in server mode successfully; otherwise false. ```APIDOC ## StartServer() ### Description Starts a server. ### Method public bool StartServer() ### Returns - **bool** - returns true if NetworkManager started in server mode successfully; otherwise false. ``` -------------------------------- ### Start Network Managers for Integration Test Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTestHelpers.html Starts NetworkManager instances created by the Create method. It can create a host or a server and clients, with an optional callback executed after the server starts and before clients start. ```csharp public static bool Start(bool host, NetworkManager server, NetworkManager[] clients, NetcodeIntegrationTestHelpers.BeforeClientStartCallback callback = null, bool startServer = true) ``` -------------------------------- ### Start NetworkManager as Server Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Starts the NetworkManager in server mode. Returns true if successful. ```csharp public bool StartServer() { // Implementation details... return false; } ``` -------------------------------- ### Start NetworkManager as Client Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Starts the NetworkManager in client mode. Returns true if successful. ```csharp public bool StartClient() { // Implementation details... return false; } ``` -------------------------------- ### SetUp Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html The UnitySetUpAttribute marks this method to be invoked once per test fixture instance. It returns an IEnumerator, indicating it can be used for asynchronous setup. ```csharp public IEnumerator SetUp() ``` -------------------------------- ### Setup Is Coroutine Property Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Indicates if SetUp uses coroutines. Setting to false uses OnInlineSetUp for performance benefits when coroutines are not needed. ```csharp protected virtual bool m_SetupIsACoroutine { get; } ``` -------------------------------- ### Start Buttons and Status Labels Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/tutorials/get-started-with-ngo.html These methods provide the UI for starting network connections and displaying the current connection mode and transport type. ```csharp private void StartButtons() { if (GUILayout.Button("Host")) NetworkManager.Singleton.StartHost(); if (GUILayout.Button("Client")) NetworkManager.Singleton.StartClient(); if (GUILayout.Button("Server")) NetworkManager.Singleton.StartServer(); } private void StatusLabels() { var mode = NetworkManager.Singleton.IsHost ? "Host" : NetworkManager.Singleton.IsServer ? "Server" : "Client"; GUILayout.Label("Transport: " + NetworkManager.Singleton.NetworkConfig.NetworkTransport.GetType().Name); GUILayout.Label("Mode: " + mode); } ``` -------------------------------- ### Start NetworkManager as Host Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Starts the NetworkManager in host mode. Returns true if successful. ```csharp public bool StartHost() { // Implementation details... return false; } ``` -------------------------------- ### Start Server and Clients in Test Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Starts both the server and client instances for an integration test, provided CanStartServerAndClients() returns true. This method returns an IEnumerator for asynchronous execution. ```csharp protected IEnumerator StartServerAndClients() ``` -------------------------------- ### StartServerAndClients Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.IntegrationTestWithApproximation.html Starts the server and all associated clients for integration testing. ```APIDOC ## StartServerAndClients ### Description Starts the server and all associated clients for integration testing. ### Method `StartServerAndClients()` ``` -------------------------------- ### Replace NetworkServer.Spawn with NetworkObject.Spawn (Netcode Example) Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/migratingfromUNet.html This example shows the Netcode for GameObjects way to spawn a GameObject. It involves instantiating the prefab and then calling Spawn() on its NetworkObject component. ```csharp GameObject go = Instantiate(myPrefab, Vector3.zero, Quaternion.identity); go.GetComponent().Spawn(); ``` -------------------------------- ### StartServer Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkTransport.html Starts the network transport to listen for incoming client connections. ```APIDOC ## StartServer ### Description Starts to listening for incoming clients ### Method abstract bool ### Returns Type | Description ---|--- bool | Returns success or failure ``` -------------------------------- ### Start Single Client Network Manager Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTestHelpers.html Starts a single client NetworkManager and ensures required hooks and handlers are registered. It is recommended to use CreateAndStartNewClient() instead of calling this directly. ```csharp public static void StartOneClient(NetworkManager clientToStart) ``` -------------------------------- ### OnOneTimeSetup Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Override this method to do any one-time setup configurations for integration tests. ```APIDOC ## OnOneTimeSetup() ### Description Override this method to do any one-time setup configurations for integration tests. ### Method protected virtual void OnOneTimeSetup() ### Parameters None ``` -------------------------------- ### StartClient Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Starts and connects the given networkManager as a client while in the middle of an integration test. ```APIDOC ## StartClient ### Description Starts and connects the given networkManager as a client while in the middle of an integration test. ### Method protected IEnumerator StartClient(NetworkManager networkManager) ### Parameters #### Path Parameters - **networkManager** (NetworkManager) - Required - The network manager to start and connect. ### Returns #### Success Response - **IEnumerator** - An IEnumerator to be used in a coroutine for asynchronous execution. ``` -------------------------------- ### CanStartServerAndClients Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Allows manual control over when the server and clients are started. ```APIDOC ## CanStartServerAndClients() ### Description Override this method and return false in order to be able to manually control when the server and clients are started. ### Method Signature `protected virtual bool CanStartServerAndClients()` ### Returns - **bool**: `true` or `false` ``` -------------------------------- ### RegisterNetcodeIntegrationTest Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTestHelpers.html Can be invoked to register the Netcode integration test setup prior to starting a test. ```APIDOC ## RegisterNetcodeIntegrationTest(bool) ### Description Registers the Netcode integration test setup. This method should be invoked prior to starting a test. ### Method ``` public static void RegisterNetcodeIntegrationTest(bool registered) ``` ### Parameters #### Path Parameters - **registered** (bool) - Required - Set to true to register, or false to unregister. ``` -------------------------------- ### StartServerAndClientsWithTimeTravel Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Starts the server and clients as long as CanStartServerAndClients() returns true. ```APIDOC ## StartServerAndClientsWithTimeTravel ### Description Starts the server and clients as long as CanStartServerAndClients() returns true. ### Method protected void StartServerAndClientsWithTimeTravel() ``` -------------------------------- ### Launch Windows Client Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/tutorials/command-line-helper Use this command in the Windows Command Prompt to start your project as a client. Replace `` with the actual path to your executable. ```bash \HelloWorld.exe -mode client ``` -------------------------------- ### Client Started Event Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Callback invoked once the local client is ready. ```csharp public event Action OnClientStarted; ``` -------------------------------- ### Subscribe to OnSynchronize Event Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/basics/scenemanagement/scene-events Example of subscribing to the `SceneEventType.Synchronize` event for a client. This should be done immediately after starting the NetworkManager. ```csharp public bool ConnectPlayer() { var success = NetworkManager.Singleton.StartClient(); if (success) { NetworkManager.Singleton.SceneManager.OnSynchronize += SceneManager_OnSynchronize; } return success; } private void SceneManager_OnSynchronize(ulong clientId) { Debug.Log($ ``` -------------------------------- ### Get TickWithPartial Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkTime.html Retrieves the tick count including the fractional part, representing the time elapsed since the system started. ```csharp public double TickWithPartial { get; } ``` -------------------------------- ### Launch Windows Server Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/tutorials/command-line-helper Use this command in the Windows Command Prompt to start your project as a server. Replace `` with the actual path to your executable. ```bash \HelloWorld.exe -mode server ``` -------------------------------- ### Launch Windows Client with Log File Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/tutorials/command-line-helper Start your Windows project as a client and redirect its output to a specified log file. Replace `` with the actual path to your executable. ```bash \HelloWorld.exe -logfile log-client.txt -mode client ``` -------------------------------- ### Get Default Tick Rate for Network Manager Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Provides a default tick rate for NetworkManager instances. This virtual method can be overridden to customize the tick rate used during test setup. ```csharp protected virtual uint GetTickRate() { // Implementation details omitted for brevity return 0; } ``` -------------------------------- ### Launch Windows Server with Log File Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/tutorials/command-line-helper Start your Windows project as a server and redirect its output to a specified log file. Replace `` with the actual path to your executable. ```bash \HelloWorld.exe -logfile log-server.txt -mode server ``` -------------------------------- ### Get Default Frame Rate for Network Manager Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Provides a default frame rate for NetworkManager instances. This virtual method can be overridden to customize the frame rate used during test setup. ```csharp protected virtual int GetFrameRate() { // Implementation details omitted for brevity return 0; } ``` -------------------------------- ### CreateAndStartNewClient Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.IntegrationTestWithApproximation.html Creates and starts a new client instance, preparing it for network operations. ```APIDOC ## CreateAndStartNewClient ### Description Creates and starts a new client instance, preparing it for network operations. ### Method `CreateAndStartNewClient()` ``` -------------------------------- ### Start Server, Host, or Client Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/troubleshooting/troubleshooting.html Use these methods to initiate server, host, or client connections. Ensure the NetworkManager component is attached to a GameObject in your scene before calling these methods to avoid NullReferenceException. ```csharp NetworkManager.Singleton.StartServer() NetworkManager.Singleton.StartHost() NetworkManager.Singleton.StartClient() ``` -------------------------------- ### Handle Ownership Request and Response in C# Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/components/core/networkobject-ownership.html Implement `OnOwnershipRequested` to approve or deny ownership requests and `OnOwnershipRequestResponse` to handle the outcome of a request. This example demonstrates how to manage ownership in a distributed authority setup. ```csharp /* * When the NetworkObject's permissions includes the OwnershipPermissions.RequestRequired flag. */ public class RequestableOwnershipBehaviour : NetworkBehaviour { public override void OnNetworkSpawn() { NetworkObject.OnOwnershipRequested += OnOwnershipRequested; NetworkObject.OnOwnershipRequestResponse += OnOwnershipRequestResponse; base.OnNetworkSpawn(); } public void TakeOwnership() { if (IsOwner) { return; } var requestStatus = NetworkObject.RequestOwnership(); if (requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent) { // Request was sent to the owning client! } else { // Request failed to send. Use the requestStatus variable to investigate the failure to send. } } private bool OnOwnershipRequested(ulong requestingClientId) { // The existing owner of the object can use this callback to choose whether the request is accepted. return true; } private void OnOwnershipRequestResponse(NetworkObject.OwnershipRequestResponseStatus ownershipRequestResponseStatus) { if (ownershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Approved) { // The ownership request was approved and current client now owns this object! } else { // The ownership request either failed or was denied. Use the ownershipRequestResponseStatus variable to investigate the failure. } } public override void OnNetworkDespawn() { NetworkObject.OnOwnershipRequested -= OnOwnershipRequested; NetworkObject.OnOwnershipRequestResponse -= OnOwnershipRequestResponse; base.OnNetworkDespawn(); } } ``` -------------------------------- ### StartClient Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkTransport.html Initiates a client connection to the network server. ```APIDOC ## StartClient ### Description Connects client to the server ### Method abstract bool ### Returns Type | Description ---|--- bool | Returns success or failure ``` -------------------------------- ### OnStart Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.TimeoutFrameCountHelper.html A virtual method that can be overridden to set up derived classes when the helper is started. ```APIDOC ## OnStart() ### Description Virtual method to override in order to setup a derived class when started. ``` -------------------------------- ### Launch macOS Client Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/tutorials/command-line-helper Use this command in the macOS Terminal to start your project as a client. Replace `` and `` with your specific details. The `-logfile -` argument directs output to standard output. ```bash /HelloWorld.app/Contents/MacOS/ -mode client -logfile - ``` -------------------------------- ### StartClient() Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.Transports.SinglePlayer.SinglePlayerTransport.html Connects client to the server. This will always return false for SinglePlayerTransport; always use StartServer(). ```APIDOC ## Method: StartClient() ### Description Connects client to the server. ### Declaration ```csharp public override bool StartClient() ``` ### Returns - **Type**: bool - **Description**: Returns success or failure. ### Remarks This will always return false for SinglePlayerTransport. Always use StartServer(). ### Overrides NetworkTransport.StartClient() ``` -------------------------------- ### Launch macOS Server Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/tutorials/command-line-helper Use this command in the macOS Terminal to start your project as a server. Replace `` and `` with your specific details. The `-logfile -` argument directs output to standard output. ```bash /HelloWorld.app/Contents/MacOS/ -mode server -logfile - ``` -------------------------------- ### StartClient Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.Transports.UTP.UnityTransport.html Connects the client to the server. Returns false if the client is already started or if port binding fails. ```APIDOC ## StartClient() ### Description Connects client to the server Note: When this method returns false it could mean: * You are trying to start a client that is already started * It failed during the initial port binding when attempting to begin to connect ### Method public override bool StartClient() ### Returns - **bool** - true if the client was started and false if it failed to start the client ### Overrides NetworkTransport.StartClient() ``` -------------------------------- ### InstantiateSetDataAndSpawn Example Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/advanced-topics/network-prefab-handler.html This method is used when instantiating from a user script for a host, server, or distributed authority client. It handles setting data and spawning the network object. ```csharp instance.GetComponent().Spawn(); return instance; } ``` -------------------------------- ### OnNetworkDespawn Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.Components.NetworkTransform.html Gets called when the NetworkObject gets despawned. This method runs both client and server side. ```APIDOC ## OnNetworkDespawn() ### Description Gets called when the NetworkObject gets despawned. This method runs both client and server side. ### Declaration ```csharp public override void OnNetworkDespawn() ``` ### Overrides NetworkBehaviour.OnNetworkDespawn() ``` -------------------------------- ### OnNetworkSpawn Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.Components.NetworkTransform.html Gets called when the NetworkObject gets spawned, message handlers are ready to be registered, and the network is set up. ```APIDOC ## OnNetworkSpawn() ### Description Gets called when the NetworkObject gets spawned, message handlers are ready to be registered, and the network is set up. ### Declaration ```csharp public override void OnNetworkSpawn() ``` ### Overrides NetworkBehaviour.OnNetworkSpawn() ``` -------------------------------- ### StartOneClient Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTestHelpers.html Starts a single client NetworkManager and ensures the required hooks and handlers are registered. It is recommended to use CreateAndStartNewClient() instead of calling this directly. ```APIDOC ## StartOneClient(NetworkManager) ### Description Starts a single client NetworkManager and ensures the required hooks and handlers are registered. It is recommended to use CreateAndStartNewClient() instead of calling this directly. ### Method ``` public static void StartOneClient(NetworkManager clientToStart) ``` ### Parameters #### Path Parameters - **clientToStart** (NetworkManager) - Required - The NetworkManager instance to start. ``` -------------------------------- ### Started Method Declaration Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.IConditionalPredicate.html Indicates that a condition check has started. Used to manage the lifecycle of conditional predicates in tests. ```csharp void Started() ``` -------------------------------- ### OnInlineSetup Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Called before creating and starting the server and clients. This is used for AllTests and PerTest modes. If access to NetworkManagers is needed, override OnServerAndClientsCreated(). ```APIDOC ## OnInlineSetup() ### Description Called before creating and starting the server and clients. This is used for AllTests and PerTest modes. If access to NetworkManagers is needed, override OnServerAndClientsCreated(). ### Method protected virtual void OnInlineSetup() ### Parameters None ``` -------------------------------- ### Launch Windows Server and Client on Single Line Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/tutorials/command-line-helper Combine server and client launch commands on a single line in the Windows Command Prompt for simultaneous execution. Replace `` with the actual path to your executable. ```bash \HelloWorld.exe -mode server & \HelloWorld.exe -mode client ``` -------------------------------- ### CreateAndStartNewClient Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Creates, starts, and connects a new client during an active integration test. ```APIDOC ## CreateAndStartNewClient() ### Description This will create, start, and connect a new client while in the middle of an integration test. ### Method Signature `protected IEnumerator CreateAndStartNewClient()` ### Returns - **IEnumerator**: An IEnumerator to be used in a coroutine for asynchronous execution. ``` -------------------------------- ### Start Network Client in Test Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Starts and connects a NetworkManager as a client within an integration test. This method returns an IEnumerator for asynchronous execution. ```csharp protected IEnumerator StartClient(NetworkManager networkManager) ``` -------------------------------- ### OnInitialize() Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.AnticipatedNetworkVariable-1.html Initializes the network variable, setting up initial values and registering with the anticipation system. ```APIDOC ## OnInitialize() ### Description Initializes the network variable, setting up initial values and registering with the anticipation system ### Overrides NetworkVariableBase.OnInitialize() ``` -------------------------------- ### Started Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.ConditionalPredicateBase.html This method is called to indicate that the process of waiting for the condition has started. It is typically called at the beginning of a conditional check in an integration test. ```csharp public void Started() ``` -------------------------------- ### Subscribe to Unload Events Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkSceneManager.html Subscribe to OnUnload to be notified when a Unload event is started by the server. Do not start new scene events within callbacks. ```csharp public event NetworkSceneManager.OnUnloadDelegateHandler OnUnload ``` -------------------------------- ### NetworkVariable Permissions Example Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/basics/networkvariable Demonstrates various NetworkVariable permission configurations for player state. Includes default permissions, owner-only read/write, everyone read/owner write, and owner read/server write. ```csharp public class PlayerState : NetworkBehaviour { private const float k_DefaultHealth = 100.0f; /// /// Default Permissions: Everyone can read, server can only write /// Player health is typically something determined (updated/written to) on the server /// side, but a value everyone should be synchronized with (that is, read permissions). /// public NetworkVariable Health = new NetworkVariable(k_DefaultHealth); /// /// Owner Read Permissions: Owner or server can read /// Owner Write Permissions: Only the Owner can write /// A player's ammo count is something that you might want, for convenience sake, the /// client-side to update locally. This might be because you are trying to reduce /// bandwidth consumption for the server and all non-owners/ players or you might be /// trying to incorporate a more client-side "hack resistant" design where non-owners /// are never synchronized with this value. /// public NetworkVariable AmmoCount = new NetworkVariable(default, NetworkVariableReadPermission.Owner, NetworkVariableWritePermission.Owner); /// /// Owner Write & Everyone Read Permissions: /// A player's model's skin selection index. You might have the option to allow players /// to select different skin materials as a way to further encourage a player's personal /// association with their player character. It would make sense to make the permissions /// setting of the NetworkVariable such that the client can change the value, but everyone /// will be notified when it changes to visually reflect the new skin selection. /// public NetworkVariable SkinSelectionIndex = new NetworkVariable(default, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); /// /// Owner Read & Server Write Permissions: /// You might incorporate some form of reconnection logic that stores a player's state on /// the server side and can be used by the client to reconnect a player if disconnected /// unexpectedly. In order for the client to let the server know it's the "same client" /// you might have implemented a keyed array (that is, Hashtable, Dictionary, etc, ) to track /// each connected client. The key value for each connected client would only be written to /// the each client's PlayerState.ReconnectionKey. Under this scenario, you only want the /// server to have write permissions and the owner (client) to be synchronized with this /// value (via owner only read permissions). /// public NetworkVariable ReconnectionKey = new NetworkVariable(default, NetworkVariableReadPermission.Owner, NetworkVariableWritePermission.Server); } ``` -------------------------------- ### Create Server and Default Number of Clients Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Initializes a server and the default number of client instances for an integration test. ```csharp protected void CreateServerAndClients() { // Implementation details omitted for brevity } ``` -------------------------------- ### OnLoad Event Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkSceneManager.html Invoked when a Load event is started by the server. Both server and clients receive this notification. Do not start new scene events within this callback. ```csharp public event NetworkSceneManager.OnLoadDelegateHandler OnLoad ``` -------------------------------- ### NetworkObject Parenting Example Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/components/helper/attachablebehaviour.html Demonstrates the traditional approach of spawning two NetworkPrefab instances and parenting one under the other. ```csharp var networkObject1 = Instantiate(networkPrefab1); var networkObject2 = Instantiate(networkPrefab2); networkObject2.transform.SetParent(networkObject1.transform); ``` -------------------------------- ### Get NetworkBehaviour Order Index Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkObject.html Gets the order index of a specific NetworkBehaviour instance within the ChildNetworkBehaviours collection. Returns 0 if the instance is not found. ```csharp public ushort GetNetworkBehaviourOrderIndex(NetworkBehaviour instance) ``` -------------------------------- ### CanStartServerAndClients Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Override this method and return false to manually control the start of the server and clients during integration tests. Returns true by default, allowing automatic startup. ```csharp protected virtual bool CanStartServerAndClients() ``` -------------------------------- ### Get VarInt Size Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.Arithmetic.html Gets the output size in bytes after VarInting an unsigned integer. Use this to determine the space required for VarInt encoded data. ```csharp public static int VarIntSize(ulong value) ``` -------------------------------- ### Synchronized RPC Driven Field Example Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/components/core/networkbehaviour-synchronize.html This example demonstrates using NetworkBehaviour.OnSynchronize to synchronize late-joining clients and an RPC to synchronize state changes for connected clients. ```csharp using UnityEngine; using Unity.Netcode; /// /// Simple RPC driven state that shows one /// form of NetworkBehaviour.OnSynchronize usage /// public class SimpleRpcState : NetworkBehaviour { private bool m_ToggleState; /// /// Late joining clients will be synchronized /// to the most current m_ToggleState. /// protected override void OnSynchronize(ref BufferSerializer serializer) { serializer.SerializeValue(ref m_ToggleState); base.OnSynchronize(ref serializer); } public void ToggleState(bool stateIsSet) { m_ToggleState = stateIsSet; } /// /// Synchronizes connected clients with the /// server-side m_ToggleState. /// /// [Rpc(SendTo.ClientsAndHost)] private void ToggleStateClientRpc(bool stateIsSet) { m_ToggleState = stateIsSet; } } ``` -------------------------------- ### InstantiateAndSpawn Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkSpawnManager.html A utility method to instantiate and spawn a network prefab, handling overrides and network synchronization. Allows specifying owner, scene destruction, player object status, and initial position/rotation. ```csharp public NetworkObject InstantiateAndSpawn(NetworkObject networkPrefab, ulong ownerClientId = 0, bool destroyWithScene = false, bool isPlayerObject = false, bool forceOverride = false, Vector3 position = default, Quaternion rotation = default) ``` -------------------------------- ### Start Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.TimeoutHelper.html Initiates the timeout tracking process. This method should be invoked to begin monitoring the elapsed time. ```csharp public void Start() ``` -------------------------------- ### Start Server and Clients with Time Travel Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Starts server and client instances for a time travel integration test, provided CanStartServerAndClients() returns true. This method does not return an IEnumerator. ```csharp protected void StartServerAndClientsWithTimeTravel() ``` -------------------------------- ### Create Server and Specific Number of Clients Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Initializes a server and a specified number of client instances for an integration test. ```csharp protected void CreateServerAndClients(int numberOfClients) { // Implementation details omitted for brevity } ``` -------------------------------- ### Custom NetworkVariable Implementation Example Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/basics/networkvariable Illustrates how to implement a custom NetworkVariable type for complex scenarios. The example shows custom serialization and deserialization logic within the NetworkSerialize method. ```csharp public class AreaWeaponBooster : NetworkBehaviour { public ApplyWeaponBooster ApplyWeaponBooster; public override void NetworkSerialize(BufferSerializer serializer) { if (serializer.IsWriter) { ApplyWeaponBooster.NetworkSerialize(serializer); } else { ApplyWeaponBooster = new ApplyWeaponBooster(); ApplyWeaponBooster.NetworkSerialize(serializer); } } } public class ApplyWeaponBooster : INetworkSerializable { public int SomeValue; public float AnotherValue; public void NetworkSerialize(BufferSerializer serializer) { serializer.SerializeValue(ref SomeValue); serializer.SerializeValue(ref AnotherValue); } } ``` -------------------------------- ### Start Client Connection Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkTransport.html Initiates a client connection to the server. Returns true if the connection attempt was successful, false otherwise. ```csharp public abstract bool StartClient() ``` -------------------------------- ### Subscribe to Synchronize Events Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkSceneManager.html Subscribe to OnSynchronize to be notified when a Synchronize event starts after a client is approved. This event synchronizes the client with loaded scenes and NetworkObjects. Do not start new scene events within callbacks. ```csharp public event NetworkSceneManager.OnSynchronizeDelegateHandler OnSynchronize ``` -------------------------------- ### HelloWorldManager.cs Script Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/tutorials/get-started-with-ngo.html This script adds a component to the NetworkManager GameObject to provide runtime UI buttons for starting as Host, Client, or Server, and displays connection status. ```csharp using Unity.Netcode; using UnityEngine; namespace HelloWorld { /// /// Add this component to the same GameObject as /// the NetworkManager component. /// public class HelloWorldManager : MonoBehaviour { private NetworkManager m_NetworkManager; private void Awake() { m_NetworkManager = GetComponent(); } private void OnGUI() { GUILayout.BeginArea(new Rect(10, 10, 300, 300)); if (!m_NetworkManager.IsClient && !m_NetworkManager.IsServer) { StartButtons(); } else { StatusLabels(); SubmitNewPosition(); } GUILayout.EndArea(); } private void StartButtons() { if (GUILayout.Button("Host")) m_NetworkManager.StartHost(); if (GUILayout.Button("Client")) m_NetworkManager.StartClient(); if (GUILayout.Button("Server")) m_NetworkManager.StartServer(); } private void StatusLabels() { var mode = m_NetworkManager.IsHost ? "Host" : m_NetworkManager.IsServer ? "Server" : "Client"; GUILayout.Label("Transport: " + m_NetworkManager.NetworkConfig.NetworkTransport.GetType().Name); GUILayout.Label("Mode: " + mode); } private void SubmitNewPosition() { if (GUILayout.Button(m_NetworkManager.IsServer ? "Move" : "Request Position Change")) { if (m_NetworkManager.IsServer && !m_NetworkManager.IsClient) { foreach (ulong uid in m_NetworkManager.ConnectedClientsIds) m_NetworkManager.SpawnManager.GetPlayerNetworkObject(uid).GetComponent().Move(); } else { var playerObject = m_NetworkManager.SpawnManager.GetLocalPlayerObject(); var player = playerObject.GetComponent(); player.Move(); } } } } } ``` -------------------------------- ### GetNetworkDriver() Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.Transports.UTP.UnityTransport.html Gets a reference to the NetworkDriver. ```APIDOC ## GetNetworkDriver() ### Description Gets a reference to the NetworkDriver. ### Returns - **NetworkDriver**: ref NetworkDriver ``` -------------------------------- ### IsHost Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Gets if we are running as host. ```APIDOC ## IsHost ### Description Gets if we are running as host. ### Property Type bool ``` -------------------------------- ### CustomMessagingManager Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Gets the CustomMessagingManager for this NetworkManager. ```APIDOC ## CustomMessagingManager ### Description Gets the CustomMessagingManager for this NetworkManager. ### Property Type CustomMessagingManager ``` -------------------------------- ### GetNetworkDriver Reference Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.Transports.UTP.UnityTransport.html Gets a reference to the NetworkDriver. ```csharp public ref NetworkDriver GetNetworkDriver() ``` -------------------------------- ### LocalClient Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Gets the local NetworkClient for this client. ```APIDOC ## LocalClient ### Description Gets the local NetworkClient for this client. ### Property Type NetworkClient ``` -------------------------------- ### IsServer Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Gets Whether or not a server is running. ```APIDOC ## IsServer ### Description Gets Whether or not a server is running. ### Property Type bool ``` -------------------------------- ### UNet Command and ClientRPC Example Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/manual/migratingfromUNet.html Illustrates UNet's Command and ClientRPC attributes for server and client communication. ```csharp [Command] public void CmdExample(float x) { Debug.Log(“Runs on server”); } [ClientRpc] public void RpcExample(float x) { Debug.Log(“Runs on clients”); } ``` -------------------------------- ### OnOneTimeSetup Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Override this method to perform any one-time setup configurations for the integration test. ```csharp protected virtual void OnOneTimeSetup() ``` -------------------------------- ### IsClient Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.NetworkManager.html Gets Whether or not a client is running. ```APIDOC ## IsClient ### Description Gets Whether or not a client is running. ### Property Type bool ``` -------------------------------- ### OnStart Virtual Method Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.TimeoutHelper.html A virtual method that can be overridden to set up derived classes when the TimeoutHelper starts. ```csharp protected virtual void OnStart() ``` -------------------------------- ### GetRotation Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.Components.NetworkRigidbodyBase.html Gets the current rotation of the Rigidbody. ```APIDOC ## GetRotation() ### Description Gets the rotation of the Rigidbody ### Method public Quaternion GetRotation() ### Returns - **Quaternion**: Quaternion ``` -------------------------------- ### OnSetup Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.TestHelpers.Runtime.NetcodeIntegrationTest.html Called before creating and starting the server and clients. Note: For AllTests and PerTest mode integration tests. For those two modes, if you want to have access to the server or client NetworkManagers then override OnServerAndClientsCreated(). ```APIDOC ## OnSetup() ### Description Called before creating and starting the server and clients. Note: For AllTests and PerTest mode integration tests. For those two modes, if you want to have access to the server or client NetworkManagers then override OnServerAndClientsCreated(). ### Method protected virtual IEnumerator OnSetup() ### Returns - IEnumerator: IEnumerator ### Parameters None ``` -------------------------------- ### GetPosition Source: https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects%402.11/api/Unity.Netcode.Components.NetworkRigidbodyBase.html Gets the current position of the Rigidbody. ```APIDOC ## GetPosition() ### Description Gets the position of the Rigidbody ### Method public Vector3 GetPosition() ### Returns - **Vector3**: Vector3 ```