### Start method for jobified server Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html The Start method initializes the NetworkDriver and connection list, binds to port 7777, and starts listening. It logs an error and returns if binding fails. ```csharp void Start() { m_Driver = NetworkDriver.Create(); m_Connections = new NativeList(16, Allocator.Persistent); var endpoint = NetworkEndpoint.AnyIpv4.WithPort(7777); if (m_Driver.Bind(endpoint) != 0) { Debug.LogError("Failed to bind to port 7777."); return; } m_Driver.Listen(); } ``` -------------------------------- ### Start method with NativeArray connection Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Creates the driver and NativeArray with Allocator.Persistent, connects to LoopbackIpv4 port 7777. ```csharp void Start() { m_Driver = NetworkDriver.Create(); m_Connection = new NativeArray(1, Allocator.Persistent); var endpoint = NetworkEndpoint.LoopbackIpv4.WithPort(7777); m_Connection[0] = m_Driver.Connect(endpoint); } ``` -------------------------------- ### Bind and listen code walkthrough Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html This snippet shows the code that binds the driver to a network address and port, and then calls Listen. It is part of the Start method and is explained in the code walkthrough. ```csharp var endpoint = NetworkEndpoint.AnyIpv4.WithPort(7777); if (m_Driver.Bind(endpoint) != 0) { Debug.LogError("Failed to bind to port 7777."); return; } m_Driver.Listen(); ``` -------------------------------- ### Create ServerBehaviour.cs initial script Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Initial C# script created in the Unity Editor named ServerBehaviour.cs. It contains empty Start and Update methods. ```csharp using System.Collections; using System.Collections.Generic; using UnityEngine; public class ServerBehaviour : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } } ``` -------------------------------- ### Client Update loop start Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Schedules the driver update and checks if the connection is still created before processing events. ```csharp void Update() { m_Driver.ScheduleUpdate().Complete(); if (!m_Connection.IsCreated) { return; } ``` -------------------------------- ### Handle Data event Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Starts the Data event handling block. ```csharp if (cmd == NetworkEvent.Type.Data) { ``` -------------------------------- ### ClientBehaviour.cs skeleton Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Defines the client MonoBehaviour with a NetworkDriver and a single NetworkConnection. The Start, OnDestroy, and Update methods are initially empty. ```csharp using UnityEngine; using Unity.Networking.Transport; public class ClientBehaviour : MonoBehaviour { NetworkDriver m_Driver; NetworkConnection m_Connection; void Start() { } void OnDestroy() { } void Update() { } } ``` -------------------------------- ### Host connecting with DTLS protocol using Unity Relay Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Initializes Unity services, signs in anonymously, creates an allocation for up to 10 connections, converts to Relay server data with 'dtls', gets a join code, and creates a NetworkDriver with relay parameters. The driver is bound and listens. ```csharp // Initialize services and sign in. await UnityServices.InitializeAsync(); await AuthenticationService.Instance.SignInAnonymouslyAsync(); // Create an allocation (for a maximum of 10 connections). var allocation = await RelayService.Instance.CreateAllocationAsync(10); var serverData = AllocationUtils.ToRelayServerData(allocation, "dtls"); // Request a join code that will need to be sent to the client out-of-band. var joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId); // Create the driver. var settings = new NetworkSettings(); settings.WithRelayParameters(ref serverData); var driver = NetworkDriver.Create(settings); driver.Bind(NetworkEndpoint.AnyIpv4); driver.Listen(); ``` -------------------------------- ### Create WebSocket NetworkDriver Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Creates a NetworkDriver using the WebSocketNetworkInterface, binds it to any IPv4 address on port 7778, and starts listening. Error handling is omitted for brevity; production code should check Bind and Listen return values. ```csharp var wsDriver = NetworkDriver.Create(new WebSocketNetworkInterface()); wsDriver.Bind(NetworkEndpoint.AnyIpv4.WithPort(7778)); wsDriver.Listen(); ``` -------------------------------- ### Create UDP NetworkDriver Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Creates a NetworkDriver using the UDPNetworkInterface, binds it to any IPv4 address on port 7777, and starts listening. Error handling is omitted for brevity; production code should check Bind and Listen return values. ```csharp var udpDriver = NetworkDriver.Create(new UDPNetworkInterface()); udpDriver.Bind(NetworkEndpoint.AnyIpv4.WithPort(7777)); udpDriver.Listen(); ``` -------------------------------- ### Create IPv4 NetworkDriver Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Creates a NetworkDriver bound to any IPv4 address on port 7777 and starts listening. This is the first step in setting up a MultiNetworkDriver that accepts both IPv4 and IPv6 connections. ```csharp var ipv4Driver = NetworkDriver.Create(); ipv4Driver.Bind(NetworkEndpoint.AnyIpv4.WithPort(7777)); ipv4Driver.Listen(); ``` -------------------------------- ### Create IPv6 NetworkDriver Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Creates a NetworkDriver bound to any IPv6 address on port 7777 and starts listening. This is the second step in setting up a MultiNetworkDriver that accepts both IPv4 and IPv6 connections. ```csharp var ipv6Driver = NetworkDriver.Create(); ipv6Driver.Bind(NetworkEndpoint.AnyIpv6.WithPort(7777)); ipv6Driver.Listen(); ``` -------------------------------- ### Jobified server MonoBehaviour skeleton Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Shows the overall structure of the server MonoBehaviour with the added JobHandle field for tracking ongoing jobs. The Start, OnDestroy, and Update methods are placeholders to be filled in as described in the following sections. ```csharp public class JobifiedServerBehaviour : MonoBehaviour { NetworkDriver m_Driver; NativeList m_Connections; JobHandle m_ServerJobHandle; void Start() { ... } void OnDestroy() { ... } void Update() { ... } } ``` -------------------------------- ### Update loop with job handle completion Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Starts the update loop by completing the previous frame's job handle. The rest of the loop is omitted (indicated by ellipsis). ```csharp void Update() { m_ClientJobHandle.Complete(); ... ``` -------------------------------- ### Receive pipeline information with PopEvent Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/pipelines-usage.html Retrieves the pipeline on which a message was received using the last argument of PopEvent or PopEventForConnection. The example checks for NetworkEvent.Type.Data and then processes the message using the receivePipeline variable. ```csharp var eventType = driver.PopEvent(out _, out _, out var receivePipeline); if (eventType == NetworkEvent.Type.Data) { // Data message was received on the receivePipeline pipeline. } ``` -------------------------------- ### Get maximum payload size from DataStreamWriter Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/faq.html Two ways to obtain the maximum payload size: by subtracting header overhead from the MTU, or by checking the capacity of a DataStreamWriter during a send operation. The first method only works if the max message size was not modified. ```csharp // 1. Directly by substracting headers from the MTU. // (Only works if max message size was not modified, see question below.) var maxPayloadSize = NetworkParameterConstants.MaxMessageSize - driver.MaxHeaderSize(pipeline); // 2. By looking at the capacity of a DataStreamWriter. driver.BeginSend(pipeline, connection, out var writer); var maxPayloadSize = writer.Capacity; driver.AbortSend(writer); ``` -------------------------------- ### Configure secure client with NetworkSettings and NetworkDriver Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-secure.html Configure a secure client by creating a NetworkSettings object with WithSecureServerParameters, providing the server name and CA certificate. Then create the NetworkDriver with those settings. ```csharp void Start () { var settings = new NetworkSettings(); settings.WithSecureServerParameters( serverName: SecureParameters.ServerCommonName, caCertificate: SecureParameters.MyGameClientCA); m_Driver = NetworkDriver.Create(settings); // ... } ``` -------------------------------- ### Configure secure server with NetworkSettings and NetworkDriver Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-secure.html Configure a secure server by creating a NetworkSettings object with WithSecureServerParameters, passing the certificate and private key. Then create the NetworkDriver with those settings and include the Unity.Networking.Transport.TLS namespace. ```csharp void Start () { var settings = new NetworkSettings(); settings.WithSecureServerParameters( certificate: SecureParameters.MyGameServerCertificate, privateKey: SecureParameters.myGameServerPrivateKey); // ... } ``` ```csharp m_Driver = NetworkDriver.Create(settings); ``` ```csharp using Unity.Networking.Transport.TLS; ``` -------------------------------- ### Accept new connections with m_Driver.Accept() Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Accepts new connections from the driver and adds them to the connection list, logging each accepted connection. ```csharp // Accept new connections. NetworkConnection c; while ((c = m_Driver.Accept()) != default) { m_Connections.Add(c); Debug.Log("Accepted a connection."); } ``` -------------------------------- ### Configure SimulatorPipelineStage with NetworkSettings Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/pipelines-usage.html Creates a NetworkDriver with simulator stage parameters to simulate network conditions like delay and packet loss. Configure maxPacketCount, mode, and packetDelayMs before creating the pipeline. ```csharp var settings = new NetworkSettings(); settings.WithSimulatorStageParameters( maxPacketCount: 100, mode: ApplyMode.AllPackets, packetDelayMs: 50); var driver = NetworkDriver.Create(settings); var simulatorPipeline = driver.CreatePipeline(typeof(SimulatorPipelineStage)); ``` -------------------------------- ### Connecting a client Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Creates a NetworkDriver and connects to the server's loopback address on port 7777. ```csharp void Start() { m_Driver = NetworkDriver.Create(); var endpoint = NetworkEndpoint.LoopbackIpv4.WithPort(7777); m_Connection = m_Driver.Connect(endpoint); } ``` -------------------------------- ### Add client driver to MultiNetworkDriver and connect Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Shows how to create a NetworkDriver, add it to a MultiNetworkDriver, and connect to a server endpoint. Use this when you need to share networking code between server and client builds by using MultiNetworkDriver as a container for client drivers. ```csharp var clientDriver = NetworkDriver.Create(); var multiDriver = MultiNetworkDriver.Create(); var driverId = multiDriver.AddDriver(clientDriver); var connection = multiDriver.Connect(driverId, serverEndpoint); ``` -------------------------------- ### Define SecureParameters class for secure connection Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-secure.html Boilerplate C# class to hold the server common name, CA certificate, server certificate, and private key. Place this file in the same folder as the minimal server and client scripts, and replace the placeholder contents with the actual PEM file contents. ```csharp public static class SecureParameters { // Use the common name you used to create the server certificate. public static readonly string ServerCommonName = "localserver"; public static readonly string MyGameClientCA = @"-----BEGIN CERTIFICATE----- *** Contents of myGameClientCA.pem *** -----END CERTIFICATE-----"; public static readonly string MyGameServerCertificate = @"-----BEGIN CERTIFICATE----- *** Contents of myGameServerCertificate.pem *** -----END CERTIFICATE-----"; public static readonly string MyGameServerPrivateKey = @"-----BEGIN RSA PRIVATE KEY----- *** Contents of myGameServerPrivateKey.pem *** -----END RSA PRIVATE KEY-----"; } ``` -------------------------------- ### Configure WSS server with WithSecureServerParameters Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/websockets.html Configure a WebSocket server to use WSS with an official certificate and key read from files. Self-signed certificates are not allowed by web browsers. ```csharp // Actual file location will depend on your specific setup. var cert = System.IO.ReadAllText("/etc/letsencrypt/live/your-domain.com/fullchain.pem"); var key = System.IO.ReadAllText("/etc/letsencrypt/live/your-domain.com/privkey.pem"); var settings = new NetworkSettings(); settings.WithSecureServerParameters(certificate: cert, privateKey: key); var driver = NetworkDriver.Create(new WebSocketNetworkInterface(), settings); ``` -------------------------------- ### Configure WSS client with WithSecureClientParameters Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/websockets.html Configure a WebSocket client to use WSS. Only the server name is required; UTP defers to the OS or browser's trust store for certificate verification. ```csharp var settings = new NetworkSettings(); settings.WithSecureClientParameters(serverName: "your-domain.com"); var driver = NetworkDriver.Create(new WebSocketNetworkInterface(), settings); ``` -------------------------------- ### Create ClientUpdateJob instance Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Creates a new job instance, passing the driver and connection. ```csharp var job = new ClientUpdateJob { Driver = m_Driver, Connection = m_Connection, }; ``` -------------------------------- ### Client connecting with WebSocket protocol using Unity Relay Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Initializes Unity services, signs in anonymously, joins an allocation using a join code, converts to Relay server data with 'wss', and creates a NetworkDriver with a WebSocketNetworkInterface. The driver connects. ```csharp // Initialize services and sign in. await UnityServices.InitializeAsync(); await AuthenticationService.Instance.SignInAnonymouslyAsync(); // Create an allocation from a join code. var allocation = await RelayService.Instance.JoinAllocationAsync(joinCode); var serverData = AllocationUtils.ToRelayServerData(allocation, "wss"); // Create the driver. var settings = new NetworkSettings(); settings.WithRelayParameters(ref serverData); var driver = NetworkDriver.Create(new WebSocketNetworkInterface(), settings); driver.Connect(); ``` -------------------------------- ### Create pipeline with FragmentationPipelineStage and ReliableSequencedPipelineStage Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/pipelines-usage.html Creates a pipeline that fragments large messages and then delivers each fragment reliably and in order. The order of stages matters: reliable after fragmentation improves bandwidth efficiency. Place this in initialization code before any connections are made. ```csharp // In initialization code, before any connections are made. var myPipeline = driver.CreatePipeline( typeof(FragmentationPipelineStage), typeof(ReliableSequencedPipelineStage)); ``` -------------------------------- ### Create ServerUpdateConnectionsJob Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Populates the ServerUpdateConnectionsJob with the driver and connections list. This job runs first in the chain. ```csharp var connectionJob = new ServerUpdateConnectionsJob { Driver = m_Driver, Connections = m_Connections }; ``` -------------------------------- ### Create MultiNetworkDriver and add drivers Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Creates a MultiNetworkDriver and adds the previously created UDP and WebSocket drivers. After this, the multiDriver can be used like a normal NetworkDriver for accepting connections, popping events, sending messages, and scheduling updates. ```csharp var multiDriver = MultiNetworkDriver.Create(); multiDriver.AddDriver(udpDriver); multiDriver.AddDriver(wsDriver); ``` -------------------------------- ### Increase reliable pipeline window size with NetworkSettings Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/pipelines-usage.html Configure the reliable pipeline's window size to 256 when creating a NetworkDriver. Both client and server must use the same value to avoid incompatibilities. ```csharp var settings = new NetworkSettings(); settings.WithReliableStageParameters(windowSize: 256); var driver = NetworkDriver.Create(settings); var reliablePipeline = driver.CreatePipeline(typeof(ReliableSequencedPipelineStage)); ``` -------------------------------- ### Bind server to wildcard address with port 7777 Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/faq.html Binds the driver to the wildcard IPv4 address (0.0.0.0) on port 7777, allowing connections from any network interface. Use this for servers that need to accept connections from any client. ```csharp driver.Bind(NetworkEndpoint.AnyIpv4.WithPort(7777)); ``` -------------------------------- ### Add IPv4 and IPv6 drivers to MultiNetworkDriver Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Creates a MultiNetworkDriver and adds the previously created IPv4 and IPv6 drivers. After this, calling Accept on the multiDriver returns connections from both address families. ```csharp var multiDriver = MultiNetworkDriver.Create(); multiDriver.AddDriver(ipv4Driver); multiDriver.AddDriver(ipv6Driver); ``` -------------------------------- ### Configure fragmentation pipeline stage with NetworkSettings Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/pipelines-usage.html Use this snippet to create a NetworkDriver with a FragmentationPipelineStage, setting a custom payload capacity of 10000 bytes. The default is 4096 bytes, and the maximum is about 20MB, but it's optimized for a few kilobytes. Place FragmentationPipelineStage first in the pipeline chain when using multiple stages. ```csharp var settings = new NetworkSettings(); settings.WithFragmentationStageParameters(payloadCapacity: 10000); var driver = NetworkDriver.Create(settings); var fragmentedPipeline = driver.CreatePipeline(typeof(FragmentationPipelineStage)); ``` -------------------------------- ### Create per-driver pipelines for UDP and WebSocket Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Creates a UDP driver with a reliable pipeline and a WebSocket driver with a dummy reliable pipeline, then adds both to a MultiNetworkDriver. This is used when drivers have different pipeline requirements, such as WebSocket not needing reliable sequencing. ```csharp // Create a UDP driver with a reliable pipeline. var udpDriver = NetworkDriver.Create(new UDPNetworkInterface()); var reliablePipeline = udpDriver.CreatePipeline(typeof(ReliableSequencedPipelineStage)); udpDriver.Bind(NetworkEndpoint.AnyIpv4.WithPort(7777)); udpDriver.Listen(); // Create a WebSocket driver with a "dummy" reliable pipeline. var wsDriver = NetworkDriver.Create(new WebSocketNetworkInterface()); var dummyPipeline = wsDriver.CreatePipeline(typeof(NullPipelineStage)); wsDriver.Bind(NetworkEndpoint.AnyIpv4.WithPort(7778)); wsDriver.Listen(); // Add both drivers to a new MultiNetworkDriver. var multiDriver = MultiNetworkDriver.Create(); multiDriver.AddDriver(udpDriver); multiDriver.AddDriver(wsDriver); ``` -------------------------------- ### Create multiple reliable pipelines for different data streams Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/pipelines-usage.html Create separate reliable pipelines for RPCs and chat messages to circumvent the per-pipeline limit of packets in flight. Note that ordering between pipelines is not guaranteed. ```csharp var rpcPipeline = driver.CreatePipeline(typeof(ReliableSequencedPipelineStage)); var chatPipeline = driver.CreatePipeline(typeof(ReliableSequencedPipelineStage)); ``` -------------------------------- ### Conditional NetworkDriver creation with UNITY_WEBGL Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/websockets.html Uses compiler definitions to select the appropriate network interface based on the build platform. For WebGL it uses WebSocket, otherwise UDP. ```csharp #if UNITY_WEBGL m_Driver = NetworkDriver.Create(new WebSocketNetworkInterface()); #else m_Driver = NetworkDriver.Create(new UDPNetworkInterface()); #endif ``` -------------------------------- ### Custom driver constructor for Netcode for Entities Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/ngo-transports.html Use this class to integrate a custom transport with Netcode for Entities. It implements INetworkStreamDriverConstructor and requires setting MyTransport before assigning to NetworkStreamReceiveSystem. The CreateClientDriver and CreateServerDriver methods register the driver with the driver store. ```csharp public class MyCustomTransportDriverConstructor : INetworkStreamDriverConstructor { // Will need to be set before assigning to NetworkStreamReceiveSystem. public MyCustomNetworkTransport MyTransport; public void CreateClientDriver(World world, ref NetworkDriverStore driverStore, NetDebug netDebug) { var netif = new NetworkTransportInterface(MyTransport); var driverInstance = DefaultDriverBuilder.CreateClientNetworkDriver(netif); driverStore.RegisterDriver(TransportType.Socket, driverInstance); } public void CreateServerDriver(World world, ref NetworkDriverStore driverStore, NetDebug netDebug) { var netif = new NetworkTransportInterface(MyTransport); var driverInstance = DefaultDriverBuilder.CreateServerNetworkDriver(netif); driverStore.RegisterDriver(TransportType.Socket, driverInstance); } } ``` -------------------------------- ### Create ServerUpdateJob with ToConcurrent Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Creates the ServerUpdateJob using a concurrent driver and a deferred job array for the connections. The ToConcurrent call is required for IParallelForJobDefer. ```csharp var serverUpdateJob = new ServerUpdateJob { Driver = m_Driver.ToConcurrent(), Connections = m_Connections.AsDeferredJobArray() }; ``` -------------------------------- ### Schedule client update job with job handle Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Schedules the driver update and the client job, chaining JobHandles. Avoids calling Complete on the driver schedule. ```csharp m_ClientJobHandle = m_Driver.ScheduleUpdate(); m_ClientJobHandle = job.Schedule(m_ClientJobHandle); ``` -------------------------------- ### ServerUpdateJob skeleton with IJobParallelForDefer Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Initial skeleton for a parallel server update job using IJobParallelForDefer. The Execute method is called for each connection index, but the body is empty in this first version. ```csharp struct ServerUpdateJob : IJobParallelForDefer { public void Execute(int i) { } } ``` -------------------------------- ### Sign server certificate with root CA using OpenSSL Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-secure.html Signs the server certificate with the root CA, producing the server certificate file. The resulting certificate is used for the 'certificate' parameter on the server. ```bash openssl.exe x509 -req -in myGameServerCertificateSigningRequest.pem -CA myGameClientCA.pem -CAkey clientPrivateKeyForRootCA.pem -CAcreateserial -out myGameServerCertificate.pem -days 365 -sha256 ``` -------------------------------- ### Send response with BeginSend and EndSend Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Adds 2 to the received number, begins a send with NetworkPipeline.Null (unreliable pipeline), writes the number, and ends the send. ```csharp number += 2; m_Driver.BeginSend(NetworkPipeline.Null, m_Connections[i], out var writer); writer.WriteUInt(number); m_Driver.EndSend(writer); } ``` -------------------------------- ### Server Update loop with job chain Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html The Update method completes the previous frame's jobs, creates the connection and server update jobs, and schedules them in sequence: driver update, connection job, then server update job. ```csharp void Update() { m_ServerJobHandle.Complete(); var connectionJob = new ServerUpdateConnectionsJob { Driver = m_Driver, Connections = m_Connections }; var serverUpdateJob = new ServerUpdateJob { Driver = m_Driver.ToConcurrent(), Connections = m_Connections.AsDeferredJobArray() }; m_ServerJobHandle = m_Driver.ScheduleUpdate(); m_ServerJobHandle = connectionJob.Schedule(m_ServerJobHandle); m_ServerJobHandle = serverUpdateJob.Schedule(m_Connections, 1, m_ServerJobHandle); } ``` -------------------------------- ### Update loop with ScheduleUpdate().Complete() Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Call ScheduleUpdate and Complete on the returned JobHandle inside the Update loop to synchronize the driver with the main thread before processing events. ```csharp void Update() { m_Driver.ScheduleUpdate().Complete(); } ``` -------------------------------- ### Wrap a NetworkTransport in Unity Transport Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/ngo-transports.html Creates a GameObject to hold a custom NetworkTransport, adds the transport component, wraps it in a NetworkTransportInterface, and creates a NetworkDriver that uses that interface. The resulting driver can be used like one created with the UDP or WebSocket network interfaces. ```csharp using Unity.Networking.Transport.NetcodeInterop; using UnityEngine; ... // Create a GameObject to hold the NetworkTransport. var go = new GameObject("NetcodeTransport"); GameObject.DontDestroyOnLoad(go); // Add your custom transport to the GameObject. var transport = go.AddComponent(); // Create a network interface wrapping the transport. var netif = new NetworkTransportInterface(transport); // Create a driver that uses that network interface. var driver = NetworkDriver.Create(netif); ``` -------------------------------- ### Generate root CA private key with OpenSSL Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-secure.html Generates a 2048-bit RSA private key for the root CA. This is the first step in creating the root certificate used to sign the server certificate. ```bash openssl genrsa -out clientPrivateKeyForRootCA.pem 2048 ``` -------------------------------- ### Configure WebSocket path with WithWebSocketParameters Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/websockets.html Configures the WebSocket network interface to use a specific URL path. For clients, all connection requests go to the given path; for servers, only connections to that path are allowed. The default path is "/". ```csharp var settings = new NetworkSettings(); settings.WithWebSocketParameters(path: "/some/path"); var driver = NetworkDriver.Create(new WebSocketNetworkInterface(), settings); ``` -------------------------------- ### Popping events with m_Connection.PopEvent Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Uses m_Connection.PopEvent instead of m_Driver.PopEventForConnection to handle a single connection. The loop continues until NetworkEvent.Type.Empty. ```csharp Unity.Collections.DataStreamReader stream; NetworkEvent.Type cmd; while ((cmd = m_Connection.PopEvent(m_Driver, out stream)) != NetworkEvent.Type.Empty) { ``` -------------------------------- ### Create NetworkDriver with WebSocketNetworkInterface Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/websockets.html Explicitly creates a network driver using the WebSocket network interface, required for WebGL clients or servers. This replaces the default UDP interface. ```csharp m_Driver = NetworkDriver.Create(new WebSocketNetworkInterface()); ``` -------------------------------- ### Generate server private key with OpenSSL Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-secure.html Generates a 2048-bit RSA private key for the server. This key is used to create the server certificate signing request. ```bash openssl genrsa -out myGameServerPrivateKey.pem 2048 ``` -------------------------------- ### Bind to ephemeral port for Unity Relay Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/faq.html Binds the driver to the wildcard IPv4 address with an ephemeral port, as recommended when using Unity Relay since all communication goes through Relay servers and a known port is unnecessary. ```csharp driver.Bind(NetworkEndpoint.AnyIpv4); ``` -------------------------------- ### ClientUpdateJob.Execute with network event handling Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Moves the client Update logic into the job's Execute method. Uses Connection[0] to refer to the first element in the NativeArray. Handles Connect, Data, and Disconnect events, including sending a uint value and disconnecting on response. ```csharp public void Execute() { if (!Connection[0].IsCreated) { return; } DataStreamReader stream; NetworkEvent.Type cmd; while ((cmd = Connection[0].PopEvent(Driver, out stream)) != NetworkEvent.Type.Empty) { if (cmd == NetworkEvent.Type.Connect) { Debug.Log("We are now connected to the server."); uint value = 1; Driver.BeginSend(Connection[0], out var writer); writer.WriteUInt(value); Driver.EndSend(writer); } else if (cmd == NetworkEvent.Type.Data) { uint value = stream.ReadUInt(); Debug.Log($"Got the value {value} back from the server."); Driver.Disconnect(Connection[0]); Connection[0] = default; } else if (cmd == NetworkEvent.Type.Disconnect) { Debug.Log("Client got disconnected from the server."); Connection[0] = default; } } } ``` -------------------------------- ### Generate server certificate signing request with OpenSSL Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-secure.html Creates a certificate signing request (CSR) for the server. You will be prompted for details; the common name should be the server's hostname. ```bash openssl req -new -key myGameServerPrivateKey.pem -out myGameServerCertificateSigningRequest.pem ``` -------------------------------- ### Handling NetworkEvent.Type.Connect Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html On connection success, logs a message and sends the value 1 to the server using BeginSend/EndSend and DataStreamWriter. ```csharp if (cmd == NetworkEvent.Type.Connect) { Debug.Log("We are now connected to the server."); uint value = 1; m_Driver.BeginSend(m_Connection, out var writer); writer.WriteUInt(value); m_Driver.EndSend(writer); } ``` -------------------------------- ### Send message on pipeline with BeginSend Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/pipelines-usage.html Passes the pipeline created earlier to BeginSend so the message is processed through its stages. The writer is obtained via out var and used to write the message payload. ```csharp driver.BeginSend(myPipeline, connection, out var writer); ``` -------------------------------- ### Clean up stale connections Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Iterates the connection list and removes stale connections (those whose IsCreated is false) using RemoveAtSwapBack, adjusting the index to avoid skipping entries. ```csharp // Clean up connections. for (int i = 0; i < m_Connections.Length; i++) { if (!m_Connections[i].IsCreated) { m_Connections.RemoveAtSwapBack(i); i--; } } ``` -------------------------------- ### Set custom max message size with NetworkSettings Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/faq.html Creates a NetworkDriver with a custom maximum message size of 1200 bytes. Recommended only if the default value (1400) causes problems, as lower values reduce bandwidth efficiency. ```csharp var settings = new NetworkSettings(); settings.WithNetworkConfigParameters(maxMessageSize: 1200); var driver = NetworkDriver.Create(settings); ``` -------------------------------- ### Replace ServerBehaviour.cs with boilerplate code Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Boilerplate code for ServerBehaviour.cs that declares a NetworkDriver and a NativeList to hold connections. This is the base for the server implementation. ```csharp using UnityEngine; using Unity.Collections; using Unity.Networking.Transport; public class ServerBehaviour : MonoBehaviour { NetworkDriver m_Driver; NativeList m_Connections; void Start() { } void OnDestroy() { } void Update () { } } ``` -------------------------------- ### Configure NetworkSettings timeouts for NetworkDriver Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/faq.html Use to customize connection and disconnection timeouts when creating a NetworkDriver. With these parameters, connection fails after 5 seconds (10 attempts every 500 ms) and connections close after 10 seconds of inactivity; defaults are 1 minute (60 attempts per second) and 30 seconds. ```csharp var settings = new NetworkSettings(); settings.WithNetworkConfigParameters( connectTimeoutMS: 500, maxConnectAttempts: 10, disconnectTimeoutMS: 10000); var driver = NetworkDriver.Create(settings); ``` -------------------------------- ### Configure NetworkDriver queue capacities Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/faq.html Increases the send and receive queue capacities when creating the NetworkDriver to avoid the NetworkSendQueueFull error returned by BeginSend. The default capacity is 512; increasing it raises memory usage by about 1500 bytes per unit of capacity. ```csharp var settings = new NetworkSettings(); settings.WithNetworkConfigParameters( sendQueueCapacity: 1024 receiveQueueCapacity: 1024); var driver = NetworkDriver.Create(settings); ``` -------------------------------- ### Event loop using connection index Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html The top-level while loop that iterates over network events for a specific connection using the index passed to Execute. This replaces the previous for loop in the non-jobified version. ```csharp while ((cmd = Driver.PopEventForConnection(Connections[i], out stream)) != NetworkEvent.Type.Empty) ``` -------------------------------- ### Add pipeline to all drivers in MultiNetworkDriver Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Adds a simulator pipeline to all drivers in a MultiNetworkDriver using the CreatePipeline method. This is used when all drivers have matching pipeline configurations. ```csharp // Add a simulator pipeline to all drivers in multiDriver. multiDriver.CreatePipeline(typeof(SimulatorPipelineStage)); ``` -------------------------------- ### Read uint from stream Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Reads a uint from the stream and logs the received value. ```csharp uint number = stream.ReadUInt(); Debug.Log($"Got {number} from a client, adding 2 to it."); ``` -------------------------------- ### ServerUpdateConnectionsJob for cleanup and accept Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Job that cleans up closed connections and accepts new ones. It uses NetworkDriver and NativeList and must run before the parallel update job because connection cleanup and acceptance cannot be done in parallel. ```csharp struct ServerUpdateConnectionsJob : IJob { public NetworkDriver Driver; public NativeList Connections; public void Execute() { // Clean up connections. for (int i = 0; i < Connections.Length; i++) { if (!Connections[i].IsCreated) { Connections.RemoveAtSwapBack(i); i--; } } // Accept new connections. NetworkConnection c; while ((c = Driver.Accept()) != default) { Connections.Add(c); Debug.Log("Accepted a connection."); } } } ``` -------------------------------- ### ServerUpdateJob with NetworkDriver.Concurrent and NativeArray Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Parallel server update job using IJobParallelForDefer. It uses NetworkDriver.Concurrent to allow processing different connections in parallel and passes a NativeArray because IJobParallelForDefer only accepts NativeArray. ```csharp struct ServerUpdateJob : IJobParallelForDefer { public NetworkDriver.Concurrent Driver; public NativeArray Connections; public void Execute(int i) { } } ``` -------------------------------- ### OnDestroy method for jobified server Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html OnDestroy completes the server job handle before disposing the driver and connections to ensure proper cleanup. ```csharp void OnDestroy() { if (m_Driver.IsCreated) { m_ServerJobHandle.Complete(); m_Driver.Dispose(); m_Connections.Dispose(); } } ``` -------------------------------- ### ClientUpdateJob struct with IJob (skeleton) Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Defines the client job struct. Data inside the job is copied, so use a shared NativeArray to update the connection after the job completes. Native containers only support blittable types. ```csharp struct ClientUpdateJob : IJob { public NetworkDriver Driver; public NativeArray Connection; public void Execute() { } } ``` -------------------------------- ### Generate root CA certificate with OpenSSL Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-secure.html Creates a self-signed root certificate (CA certificate) valid for 1095 days. You will be prompted for details; the common name should be meaningful for identification, ideally your domain name. ```bash openssl req -x509 -new -nodes -key clientPrivateKeyForRootCA.pem -sha256 -days 1095 -out myGameClientCA.pem ``` -------------------------------- ### Pop events for each connection Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Loops over each connection and pops events for that connection using PopEventForConnection, retrieving a DataStreamReader for reading Data messages. The loop continues until no more events are available. ```csharp for (int i = 0; i < m_Connections.Length; i++) { DataStreamReader stream; NetworkEvent.Type cmd; while ((cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream)) != NetworkEvent.Type.Empty) { ``` -------------------------------- ### Schedule job chain Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Schedules the job chain: driver update, connection job, then server update job. The server update job uses the connections array with a batch size of 1. ```csharp m_ServerJobHandle = m_Driver.ScheduleUpdate(); m_ServerJobHandle = connectionJob.Schedule(m_ServerJobHandle); m_ServerJobHandle = serverUpdateJob.Schedule(m_Connections, 1, m_ServerJobHandle); ``` -------------------------------- ### Cleaning up the client Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Disposes the NetworkDriver in OnDestroy. No NativeList is needed for a single connection. ```csharp void OnDestroy() { m_Driver.Dispose(); } ``` -------------------------------- ### Handle Disconnect event Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Handles disconnection by logging, resetting the connection handle to default, and breaking out of the event loop. ```csharp else if (cmd == NetworkEvent.Type.Disconnect) { Debug.Log("Client disconnected from the server."); m_Connections[i] = default; break; } ``` -------------------------------- ### Disconnect and dispose NetworkDriver with update job Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/faq.html Ensure the other end is notified of a disconnection before disposing the driver. Calling Disconnect does not send immediately; an update job must run, so schedule and complete one before Dispose. ScheduleFlushSend is not sufficient because disconnections require extra cleanup work. ```csharp // Close the connection. driver.Disconnect(connection); // Schedule and complete an update job. This is required! driver.ScheduleUpdate().Complete(); // Now it's okay to dispose of the driver. driver.Dispose(); ``` -------------------------------- ### Implement OnDestroy method for server Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html The OnDestroy method disposes the NetworkDriver and NativeList if the driver is created, preventing memory leaks. The check for IsCreated ensures disposal only happens if memory was allocated. ```csharp void OnDestroy() { if (m_Driver.IsCreated) { m_Driver.Dispose(); m_Connections.Dispose(); } } ``` -------------------------------- ### Handling NetworkEvent.Type.Disconnect Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Logs a disconnect message and resets the connection to default. ```csharp else if (cmd == NetworkEvent.Type.Disconnect) { Debug.Log("Client got disconnected from server."); m_Connection = default; } ``` -------------------------------- ### Execute method for parallel server update Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Execute method for the parallel server update job. It processes network events for each connection, reading data, adding 2, and sending back the result. It also handles disconnects by setting the connection to default. ```csharp public void Execute(int i) { DataStreamReader stream; NetworkEvent.Type cmd; while ((cmd = Driver.PopEventForConnection(Connections[i], out stream)) != NetworkEvent.Type.Empty) { if (cmd == NetworkEvent.Type.Data) { uint number = stream.ReadUInt(); Debug.Log($"Got {number} from a client, adding 2 to it."); number += 2; Driver.BeginSend(Connections[i], out var writer); writer.WriteUInt(number); Driver.EndSend(writer); } else if (cmd == NetworkEvent.Type.Disconnect) { Debug.Log("Client disconnected from the server."); Connections[i] = default; } } } ``` -------------------------------- ### Send reliably through MultiNetworkDriver Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/cross-play.html Sends a value reliably through the MultiNetworkDriver using the reliable pipeline. The pipeline used depends on the underlying connection: ReliableSequencedPipelineStage for UDP, NullPipelineStage for WebSocket. ```csharp // Will send the value 42 reliably. If connection is UDP-based, then this will send // the packet through the ReliableSequencedPipelineStage. If it is WebSocket-based, // then this will send the packet through the NullPipelineStage, which does nothing. multiDriver.BeginSend(reliablePipeline, connection, out var writer); writer.WriteInt(42); multiDriver.EndSend(writer); ``` -------------------------------- ### Handling NetworkEvent.Type.Data Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-simple.html Reads the value back from the server, logs it, disconnects, and resets the connection to default to avoid stale references. ```csharp else if (cmd == NetworkEvent.Type.Data) { uint value = stream.ReadUInt(); Debug.Log($"Got the value {value} back from the server."); m_Connection.Disconnect(m_Driver); m_Connection = default; } ``` -------------------------------- ### OnDestroy method disposing NativeArray Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Completes the job handle, disposes the driver and the NativeArray. The Complete call ensures jobs finish before cleanup. ```csharp void OnDestroy() { m_ClientJobHandle.Complete(); m_Driver.Dispose(); m_Connection.Dispose(); } ``` -------------------------------- ### JobifiedClientBehaviour fields Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Updates ClientBehaviour to use NativeArray for m_Connection and adds a JobHandle m_ClientJobHandle to track ongoing jobs. ```csharp public class JobifiedClientBehaviour : MonoBehaviour { NetworkDriver m_Driver; NativeArray m_Connection; JobHandle m_ClientJobHandle; ``` -------------------------------- ### Handle NetworkSendQueueFull error when reliable pipeline is full Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/pipelines-usage.html When the reliable pipeline has reached its maximum packets in flight, EndSend returns NetworkSendQueueFull (value -5). Use this pattern to detect that error and queue the message for later resending. ```csharp driver.BeginSend(myReliablePipeline, connection, out var writer); // Write your message to the writer. if (driver.EndSend(writer) == (int)Error.StatusCode.NetworkSendQueueFull)) { // Copy your message to a queue, and try resending later. } ``` -------------------------------- ### Collections-related errors after upgrade Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/migration.html Console errors that may appear after upgrading the Collections package from version 1.2 to 2.X. Closing and restarting the editor usually resolves them. ```text Unity.Collections/NativeParallelHashSetExtensions.gen.cs(17,51): error CS0246: The type or namespace name 'NativeHashSet<>' could not be found (are you missing a using directive or an assembly reference?) Unity.Collections/UnsafeParallelHashSetExtensions.gen.cs(1084,78): error CS0246: The type or namespace name 'UnsafeHashSet<>' could not be found (are you missing a using directive or an assembly reference?) ``` -------------------------------- ### Read Disconnect event reason from DataStreamReader Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/faq.html Retrieve the reason for a Disconnect event by reading a byte from the event's DataStreamReader. The value is from the Error.DisconnectReason enum. ```csharp var eventType = driver.PopEvent(out _, out var streamReader); if (eventType == NetworkEvent.Type.Disconnect) { var disconnectReason = streamReader.ReadByte(); } ``` -------------------------------- ### Add [BurstCompile] attribute to a job Source: https://docs.unity3d.com/Packages/com.unity.transport%406.6/manual/client-server-jobs.html Add the [BurstCompile] attribute to a job struct definition to enable Burst compilation for that job. The ellipsis represents the job's fields and Execute method. ```csharp [BurstCompile] struct ClientUpdateJob : IJob { ... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.