### C# Example: RelayDriverConstructor for Network Driver Setup
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/networking-using-relay.md
This C# example demonstrates a `RelayDriverConstructor` class that implements `INetworkStreamDriverConstructor`. It configures network drivers to support both local IPC connections (for self-hosting) and Relay connections (for remote or local servers). The constructor registers client and server drivers, dynamically choosing between IPC, UDP, or WebSocket based on Relay settings and platform (WebGL vs. others).
```csharp
///
/// Register client and server using Relay server settings.
/// For the client, if the Relay settings are not set and the modality is `Client/Server`, it will
/// try to setup the driver using IPCNetworkInterface.
///
public class RelayDriverConstructor : INetworkStreamDriverConstructor
{
RelayServerData m_RelayClientData;
RelayServerData m_RelayServerData;
public RelayDriverConstructor(RelayServerData serverData, RelayServerData clientData)
{
m_RelayServerData = serverData;
m_RelayClientData = clientData;
}
///
/// This method will ensure that we register different driver types based on the Relay settings
/// settings.
///
/// Mode | Relay Settings
/// Client/Server | Valid -> use Relay to connect to local server
/// Invalid -> use IPC to connect to local server
/// Client | Always use Relay. Expect data to be valid, or exceptions are thrown by Transport.
///
///
/// For WebGL, WebSocket is always preferred for client in the Editor, to closely emulate the player behaviour.
///
///
public void CreateClientDriver(World world, ref NetworkDriverStore driverStore, NetDebug netDebug)
{
var settings = DefaultDriverBuilder.GetNetworkClientSettings();
//if the Relay data is not valid, connect via local IPC
if(ClientServerBootstrap.RequestedPlayType == ClientServerBootstrap.PlayType.ClientAndServer &&
!m_RelayClientData.Endpoint.IsValid)
{
DefaultDriverBuilder.RegisterClientIpcDriver(world, ref driverStore, netDebug, settings);
}
else
{
settings.WithRelayParameters(ref m_RelayClientData);
#if !UNITY_WEBGL
DefaultDriverBuilder.RegisterClientUdpDriver(world, ref driverStore, netDebug, settings);
#else
DefaultDriverBuilder.RegisterClientWebSocketDriver(world, ref driverStore, netDebug, settings);
#endif
}
}
public void CreateServerDriver(World world, ref NetworkDriverStore driverStore, NetDebug netDebug)
{
//The first driver is the IPC for internal client/server connection if necessary.
// IPC can't use Relay and needs to be set up without Relay data.
var ipcSettings = DefaultDriverBuilder.GetNetworkServerSettings();
DefaultDriverBuilder.RegisterServerIpcDriver(world, ref driverStore, netDebug, ipcSettings);
var relaySettings = DefaultDriverBuilder.GetNetworkServerSettings();
//The other driver (still the same port) is going to listen using Relay for external connections.
relaySettings.WithRelayParameters(ref m_RelayServerData);
#if !UNITY_WEBGL
DefaultDriverBuilder.RegisterServerUdpDriver(world, ref driverStore, netDebug, relaySettings);
#else
DefaultDriverBuilder.RegisterServerWebSocketDriver(world, ref driverStore, netDebug, relaySettings);
#endif
}
}
```
--------------------------------
### Example Netcode Source Generator Configuration File
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/source-generators.md
Illustrates the basic key-value pair format used for configuring Unity Netcode source generators, typically found in an analyzer configuration file. This example shows how to set global flags and specific key-value pairs.
```Text
is_global=true
your_key=your value
your_key=your value
...
```
--------------------------------
### Client World Input Command Packet Dump Example
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/logging.md
This snippet shows an example of an input command packet dump as seen on a client world. It details the structure and content of the ShipCommandData being sent, including command details, payload information, and bit sizes for various fields.
```text
[CSS][ShipCommandData:15257441568649283849] Sent for inputTargetTick: 262 | Entity(1205:3) on GhostInst[type:0|id:191,st:56] | isAutoTarget:True
| stableHash: 64 bits [8 bytes]
| commandSize: 16 bits [2 bytes]
| autoCommandTargetGhost: 64 bits [8 bytes]
| numCommandsToSend(4): 5 bits
[b]=[355|→-1 ↑-1] (tick: 32 bits [4 bytes]) (data: 8 bits)
[1]=[354|→-1 ↑-1] (cb: 0) (tΔ: 2 bits)
[2]=[353|→-1 ↑-1] (cb: 0) (tΔ: 2 bits)
[3]=[352|→1 ↑-1] (cb: 1) (tΔ: 2 bits) (data: 6 bits)
| payloadTicks: 38 bits [5 bytes]
| payload: 10 bits [2 bytes]
| changeBits: 3 bits
| flush: 5 bits
---
208 bits [26 bytes]
```
--------------------------------
### Server World Input Command Packet Dump Example
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/logging.md
This snippet shows an example of an input command packet dump as received and processed on a server world. It highlights the server-side interpretation of the client's input commands, including arrival and margin details.
```text
[CRS][3480158943696179440] Received command packet from Entity(623:9) on GhostInst[type:??|id:191,st:56] targeting tick 355:
| arrivalTick:353
| margin:2
[b]=[355|→-1 ↑-1]
[1]=[354|→-1 ↑-1] (cb:0)
[2]=[353|→-1 ↑-1] (cb:0)
[3]=[352|→1 ↑-1] (cb:1) Late!
---
26 bytes
```
--------------------------------
### ClientServerBootstrap Auto-Connection Configuration
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/network-connection.md
The ClientServerBootstrap class offers properties to configure automatic client connection and server listening behavior upon application startup. These properties simplify the initial network setup.
```APIDOC
ClientServerBootstrap:
AutoConnectPort: int
Description: Specifies the port for automatic connection and listening. A non-zero value enables this feature.
Type: int
DefaultConnectAddress: NetworkEndpoint
Description: The default network address for clients to connect to when AutoConnectPort is active. Defaults to NetworkEndpoint.Loopback.
Type: NetworkEndpoint
DefaultListenAddress: NetworkEndpoint
Description: The default network address for servers to listen on when AutoConnectPort is active. Defaults to NetworkEndpoint.AnyIpv4.
Type: NetworkEndpoint
```
--------------------------------
### Player Ghost Prefab Configuration Example
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/ghost-groups.md
An example configuration for a 'Player' ghost prefab, illustrating typical network synchronization properties. This includes its importance, maximum send rate, ownership prediction, dynamic nature, and the presence of a `GhostGroup` dynamic buffer for managing child ghosts.
```txt
'Player' Ghost Prefab
Importance:100, Max Send Rate:60, Owner Predicted, Has Owner, Dynamic,
RelevantWithinRadius:1km, DynamicBuffer (Count:0)
```
--------------------------------
### Default ClientServerBootstrap Initialize Method
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/client-server-worlds.md
This C# code snippet shows the default implementation of the `Initialize` method within the `ClientServerBootstrap` class. It automatically calls `CreateDefaultClientServerWorlds()` to set up client and server worlds when the game starts or enters Play mode in the Unity Editor.
```c#
public virtual bool Initialize(string defaultWorldName)
{
CreateDefaultClientServerWorlds();
return true;
}
```
--------------------------------
### Configure and Reset Network Drivers for Client and Server Worlds
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/networking-using-relay.md
This C# code demonstrates how to configure and reset network driver stores for both client and server worlds within a Unity Netcode project. It shows the setup of `NetworkDriverStore` instances, registration of different driver types (UDP, IPC, WebSocket), and the use of `NetworkStreamDriver.ResetDriverStore` to apply these configurations after world creation. The client setup specifically includes Relay parameters, while the server setup registers multiple drivers for different connection types, including Relay.
```C#
public void SetupClientWorld(World world, in RelayData relay)
{
//we assume here we want to forcibly use Relay
var settings = DefaultDriverBuilder.GetNetworkClientSettings();
settings.WithRelayParameters(ref m_RelayClientData);
var netDebug = world.EntityManager.CreateEntityQuery(typeof(NetDebug)).GetSingleton();
var driverStore = new NetworkDriverStore();
DefaultDriverBuilder.RegisterClientUdpDriver(world, ref driverStore, netDebug, settings);
var networkStreamDriver = world.EntityManager.CreateEntityQuery(typeof(NetworkStreamDriver)).GetSingleton();
networkStreamDriver.ResetDriverStore(world, ref driverStore);
}
public void SetupServerWorld(World world, in RelayData relay)
{
var driverStore = new NetworkDriverStore();
var netDebug = world.EntityManager.CreateEntityQuery(typeof(NetDebug)).GetSingleton();
var ipcSettings = DefaultDriverBuilder.GetNetworkServerSettings();
DefaultDriverBuilder.RegisterServerIpcDriver(world, ref driverStore, netDebug, ipcSettings);
var relaySettings = DefaultDriverBuilder.GetNetworkServerSettings();
//The other driver (still the same port) is going to listen using relay for external conections.
relaySettings.WithRelayParameters(ref m_RelayServerData);
DefaultDriverBuilder.RegisterServerUdpDriver(world, ref driverStore, netDebug, relaySettings);
#else
DefaultDriverBuilder.RegisterServerWebSocketDriver(world, ref driverStore, netDebug, relaySettings);
#endif
var networkStreamDriver = world.EntityManager.CreateEntityQuery(typeof(NetworkStreamDriver)).GetSingleton();
networkStreamDriver.ResetDriverStore(world, ref driverStore);
}
```
--------------------------------
### Join Unity Lobby Using a Join Code
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/host-migration/lobby-relay-integration.md
This example demonstrates how to join an existing Unity Lobby by providing its specific join code. This is one of several methods to join a lobby, alongside joining by ID or quick join.
```C#
var lobby = await LobbyService.Instance.JoinLobbyByCodeAsync("CODE");
```
--------------------------------
### Configure Thin Client Input Entity CommandTarget (C#)
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/thin-clients.md
This C# snippet demonstrates how to manually create a dummy entity for input on a thin client and assign it as the `CommandTarget` for the connection entity. This setup is necessary because thin clients do not create ghosts, which prevents `AutoCommandTarget` from functioning. The dummy entity should contain your `IInputComponentData` and its corresponding `InputBufferData`.
```C#
var myDummyGhostCharacterControllerEntity = entityManager.CreateEntity(typeof(MyNamespace.MyInputComponent), typeof(InputBufferData));
var myConnectionEntity = SystemAPI.GetSingletonEntity();
entityManager.SetComponentData(myConnectionEntity, new CommandTarget { targetEntity = myDummyGhostCharacterControllerEntity }); // This tells the netcode package which entity it should be sending inputs for.
```
--------------------------------
### Complete GoInGame.cs File Example (C#)
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/networked-cube.md
This comprehensive C# code block presents the full content of the `GoInGame.cs` file. It includes the `SetRpcSystemDynamicAssemblyListSystem` for RPC configuration and the `GoInGameRequest` struct, which defines the RPC command for clients to request entering the game state.
```C#
using UnityEngine;
using Unity.Collections;
using Unity.Entities;
using Unity.NetCode;
using Unity.Burst;
///
/// This allows sending RPCs between a stand alone build and the editor for testing purposes in the event when you finish this example
/// you want to connect a server-client stand alone build to a client configured editor instance.
///
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation | WorldSystemFilterFlags.ServerSimulation | WorldSystemFilterFlags.ThinClientSimulation)]
[UpdateInGroup(typeof(InitializationSystemGroup))]
[CreateAfter(typeof(RpcSystem))]
public partial struct SetRpcSystemDynamicAssemblyListSystem : ISystem
{
public void OnCreate(ref SystemState state)
{
SystemAPI.GetSingletonRW().ValueRW.DynamicAssemblyList = true;
state.Enabled = false;
}
}
// RPC request from client to server for game to go "in game" and send snapshots / inputs
public struct GoInGameRequest : IRpcCommand
{
}
```
--------------------------------
### Unity Netcode: NetworkStreamRequestListen (APIDOC)
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/network-connection.md
A singleton used to make the server start listening at a desired address/port on the server world. It is consumed by `NetworkStreamReceiveSystem`.
```APIDOC
NetworkStreamRequestListen:
Endpoint: Endpoint to listen on.
```
--------------------------------
### Deploy Host Migration Data to New Server World
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/host-migration/host-migration-systems.md
When a client becomes the new host, it must download the migration data and deploy it to a new server world. This snippet shows how to download the data, create a new server world with a provided driver constructor (including relay information), migrate the data into this world, and then start listening for connections.
```C#
var migrationData = await LobbyService.Instance.DownloadMigrationDataAsync(m_MigrationConfig, new LobbyDownloadMigrationDataOptions());
var allocation = await RelayService.Instance.CreateAllocationAsync(10);
var hostRelayData = allocation.ToRelayServerData("dtls");
var driverConstructor = new HostMigrationDriverConstructor(hostRelayData, new RelayServerData());
var arrayData = new NativeArray(migrationData.Data.Length, Allocator.Temp);
var slice = new NativeSlice(arrayData);
slice.CopyFrom(migrationData.Data);
if (!HostMigration.MigrateDataToNewServerWorld(driverConstructor, ref arrayData))
{
Debug.LogError($"Host migration failed while migrating data to new server world");
}
```
--------------------------------
### Override ClientServerBootstrap to Prevent Automatic World Creation
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/client-server-worlds.md
This C# example demonstrates how to extend `ClientServerBootstrap` and override its `Initialize` method. By calling `CreateLocalWorld()` instead of the default `CreateDefaultClientServerWorlds()`, it prevents the automatic creation of multiplayer-specific client and server worlds, allowing for custom world setup.
```c#
public class MyGameSpecificBootstrap : ClientServerBootstrap
{
public override bool Initialize(string defaultWorldName)
{
//Create only a local simulation world without any multiplayer and netcode system in it.
CreateLocalWorld(defaultWorldName);
return true;
}
}
```
--------------------------------
### Listening for Client Connection Events in Unity Netcode (C#)
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/network-connection.md
This example shows how to create a Burst-compiled ISystem to listen for and react to client connection events in Unity Netcode. It accesses the `ConnectionEventsForTick` collection from the `NetworkStreamDriver` singleton, emphasizing the importance of system update order within the `SimulationSystemGroup` to ensure correct event processing.
```csharp
// Example System:
[UpdateAfter(typeof(NetworkReceiveSystemGroup))]
[BurstCompile]
public partial struct NetCodeConnectionEventListener : ISystem
{
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var connectionEventsForClient = SystemAPI.GetSingleton().ConnectionEventsForTick;
foreach (var evt in connectionEventsForClient)
{
UnityEngine.Debug.Log($"[{state.WorldUnmanaged.Name}] {evt.ToFixedString()}!");
}
}
}
```
--------------------------------
### Physics Ghost Setup Checklist
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/physics.md
Guidelines for configuring physics ghosts in Unity Netcode for Entities, detailing valid and error configurations based on GhostAuthoringComponent, Rigidbody, Static, and separate physics world settings. This checklist helps ensure correct behavior for networked physics objects.
```APIDOC
Physics Ghost Setup Checklist:
| GhostAuthoringComponent | Rigidbody | Static | In a separate physics world | Result |
|-------------------------|-----------------------|--------|-----------------------------|-------------|
| yes | yes | both | no | valid |
| no | yes | no | yes | valid |
| not required | no | yes | both | valid |
| yes | both | yes | both | valid |
| no | on a child of a ghost | no | both | error |
| no | yes | no | no | error |
```
--------------------------------
### COPY_FROM_SNAPSHOT_SETUP Region Definition
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Runtime/SourceGenerators/Source~/Documentation/templates-spec.md
A placeholder region designed to contain setup code for serialization, specifically for determining if the struct is a buffer or a component.
```APIDOC
COPY_FROM_SNAPSHOT_SETUP:
Description: placeholder region that will contains the code for setting the serialization based if the struct is a buffer or component
```
--------------------------------
### C# Setup GhostDistanceData and GhostImportance Singletons
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/optimizations.md
This C# code snippet demonstrates how to initialize and add `GhostDistanceData` and `GhostImportance` as singleton components to an entity. `GhostDistanceData` configures the spatial grid for partitioning, while `GhostImportance` links to the custom scaling function and specifies the types for connection position and chunk data, enabling distance-based ghost culling.
```c#
var gridSingleton = state.EntityManager.CreateSingleton(new GhostDistanceData
{
TileSize = new int3(tileSize, tileSize, 256),
TileCenter = new int3(0, 0, 128),
TileBorderWidth = new float3(1f, 1f, 1f),
});
state.EntityManager.AddComponentData(gridSingleton, new GhostImportance
{
ScaleImportanceFunction = GhostDistanceImportance.ScaleFunctionPointer,
GhostConnectionComponentType = ComponentType.ReadOnly(),
GhostImportanceDataType = ComponentType.ReadOnly(),
GhostImportancePerChunkDataType = ComponentType.ReadOnly(),
});
```
--------------------------------
### Update RPC Registration and Queue Access to Singleton
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/upgrade-guide.md
The API to register RPCs and get RPC queues has moved from `RpcSystem` to the singleton `RpcCollection`.
```C#
// Old API location:
// RpcSystem
// New API location (singleton):
// RpcCollection
```
--------------------------------
### Gun Ghost Prefab Configuration Example
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/ghost-groups.md
An example configuration for a 'Gun' ghost prefab, detailing its network synchronization properties. This includes its importance, maximum send rate, ownership prediction, static optimization, and relevancy radius, highlighting how a child ghost might be configured before being part of a ghost group.
```txt
'Gun' Ghost Prefab
Importance:10, MaxSendRate:10, Owner Predicted, Has Owner, Static,
RelevantWithinRadius:200m
```
--------------------------------
### Configure Auto-Connect with Custom ClientServerBootstrap
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/network-connection.md
This C# code defines a custom ClientServerBootstrap class that overrides the Initialize method. It sets the AutoConnectPort to 7979, enabling automatic server listening and client connection upon world creation. This simplifies the initial setup of network communication in Netcode for Entities.
```c#
public class AutoConnectBootstrap : ClientServerBootstrap
{
public override bool Initialize(string defaultWorldName)
{
// This will enable auto connect.
AutoConnectPort = 7979;
// Create the default client and server worlds, depending on build type in a player or the PlayMode Tools in the editor
CreateDefaultClientServerWorlds();
return true;
}
}
```
--------------------------------
### Implement Connection Approval Handling Systems in Unity Netcode
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/network-connection.md
This C# code provides an example of how to set up connection approval handling in Unity Netcode. It defines an ApprovalFlow struct implementing IApprovalRpcCommand for the payload, an ApprovalStarted component to track sent requests, a ClientConnectionApprovalSystem to send approval RPCs, and a ServerConnectionApprovalSystem to validate the received RPCs and either approve or disconnect the client based on the payload.
```csharp
// The approval RPC, here it contains a hypothetical payload the server will validate
public struct ApprovalFlow : IApprovalRpcCommand
{
public FixedString512Bytes Payload;
}
// This is used to indicate we've already sent an approval RPC and don't need to do so again
public struct ApprovalStarted : IComponentData
{
}
[WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation | WorldSystemFilterFlags.ThinClientSimulation)]
public partial struct ClientConnectionApprovalSystem : ISystem
{
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate();
}
public void OnUpdate(ref SystemState state)
{
var ecb = new EntityCommandBuffer(Allocator.Temp);
// Check connections which have not yet fully connected and send connection approval message
foreach (var (connection, entity) in SystemAPI.Query>().WithNone().WithNone().WithEntityAccess())
{
var sendApprovalMsg = ecb.CreateEntity();
ecb.AddComponent(sendApprovalMsg, new ApprovalFlow { Payload = "ABC" });
ecb.AddComponent(sendApprovalMsg);
ecb.AddComponent(entity);
}
ecb.Playback(state.EntityManager);
}
}
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
public partial struct ServerConnectionApprovalSystem : ISystem
{
public void OnUpdate(ref SystemState state)
{
var ecb = new EntityCommandBuffer(Allocator.Temp);
// Check connections which have not yet fully connected and send connection approval message
foreach (var (receiveRpc, approvalMsg, entity) in SystemAPI.Query,RefRW>().WithEntityAccess())
{
var connectionEntity = receiveRpc.ValueRO.SourceConnection;
if (approvalMsg.ValueRO.Payload.Equals("ABC"))
{
ecb.AddComponent(connectionEntity);
// Destroy RPC message
ecb.DestroyEntity(entity);
}
else
{
// Failed approval messages should be disconnected
ecb.AddComponent(connectionEntity);
}
}
ecb.Playback(state.EntityManager);
}
}
```
--------------------------------
### Manually Schedule RPCs using RpcQueue in Unity Netcode
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/rpcs.md
This C# `ComponentSystem` demonstrates how to manually obtain and use an `RpcQueue` to schedule outgoing RPCs. It shows how to get the `RpcQueue` singleton and then schedule an `OurRpcCommand` using an `OutgoingRpcDataStreamBuffer` when a specific input (space bar) is detected.
```C#
[WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation)]
public class ClientQueueRpcSendSystem : ComponentSystem
{
protected override void OnCreate()
{
RequireForUpdate();
}
protected override void OnUpdate()
{
if (Input.GetKey("space"))
{
var rpcQueue = GetSingleton().GetRpcQueue();
Entities.ForEach((Entity entity, ref NetworkStreamConnection connection) =>
{
var rpcFromEntity = GetBufferLookup();
if (rpcFromEntity.Exists(entity))
{
var buffer = rpcFromEntity[entity];
rpcQueue.Schedule(buffer, new OurRpcCommand());
}
});
}
}
}
```
--------------------------------
### Download Host Migration Data in Unity C#
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/host-migration/lobby-relay-integration.md
This snippet illustrates how a new host can download migration data. It uses the MigrationDataInfo obtained earlier to retrieve the byte array containing the migration data via an HTTP GET request.
```C#
byte[] data = await LobbyService.Instance.DownloadMigrationDataAsync(info);
```
--------------------------------
### Unity Netcode: Rollback and Reconciliation Components
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/intro-to-prediction.md
Details the components involved in Unity Netcode's rollback and reconciliation process. This includes SnapshotBuffer for caching, GhostUpdateSystem for applying state updates, the Simulate tag for selective simulation, and PredictedSimulationGroup for calculating resimulation start points.
```APIDOC
SnapshotBuffer:
Description: Internal cache for incoming server snapshots containing predicted ghosts.
GhostUpdateSystem:
Description: Applies new states from received snapshots to their respective ghosts in the next frame. Only ghosts that received an update are rolled back.
Simulate:
Tag: Used to mark entities/ghosts to signal if they should be simulated or not. Essential for selective rollback strategies.
PredictedSimulationGroup:
Description: Calculates the starting tick from which resimulation should occur during rollback.
```
--------------------------------
### GhostFieldAttribute Inheritance Example
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Runtime/SourceGenerators/Source~/Documentation/code-gen-spec.md
Demonstrates how `GhostFieldAttribute` properties are inherited and overridden in nested struct scenarios. This example clarifies the precedence rules for attributes applied to parent and child fields.
```C#
public struct Child
{
public int intField;
[GhostField] public float useParentQuantization;
[GhostField(Quantization=5000)] public int useLocalQuantization;
}
public struct Parent : IComponentData
{
[GhostField(Quantization=1000)] public Child child;
[GhostField(SubType=5, Quantization=700, Smooting=Interpolate)] public float3 customFloat3;
}
```
--------------------------------
### Unity Netcode: Ensuring Stability with HostMigrationInProgress Singleton
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/host-migration/host-migration-considerations.md
Explains the importance of waiting for host migration to complete before systems initialize. It introduces the `HostMigrationInProgress` singleton component as a mechanism for systems to pause execution until the migration data is fully deployed.
```APIDOC
Unity.NetCode.HostMigrationInProgress:
Description: A singleton component present in the world when a host migration is in progress.
Usage: Systems should check for this component and early out if present to prevent premature initialization or invalid state changes during migration. It is created immediately after world creation and disappears once migration data is deployed, ensuring stability.
```
--------------------------------
### C# Composite Field Serialization Example
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Runtime/SourceGenerators/Source~/Documentation/code-gen-spec.md
Illustrates how composite struct types are recursively traversed and flattened for serialization. It shows an example of nested structs and how GhostFieldAttribute influences which fields are collected.
```c#
struct ChildChildStuct
{
public int x;
public int y;
public [GhostField(SendData=false)] int z;
}
struct ChildStuct
{
public int a;
public ChildChildStuct b;
}
public struct MySerialisedStruct : IComponentData
{
public [GhostField] int field1;
public [GhostField] ChildStuct field2;
}
```
--------------------------------
### Flattened GhostFieldAttribute Serialization Example
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Runtime/SourceGenerators/Source~/Documentation/code-gen-spec.md
Illustrates the conceptual flattened structure of data after `GhostFieldAttribute` inheritance rules are applied. This example shows how attributes from parent fields affect nested child fields during the serialization process.
```C#
struct SerializedData
{
[GhostField] public int child_intField; //<-- it is a integer, quantization does not matter
[GhostField(Quantization=1000)] public int child_useParentQuantization; //<-- this use parent quantization 1000
[GhostField(Quantization=5000)] public int child_useLocalQuantization; //<-- this use local quantization 5000
//this use the parent quantization and interpolation and the custom template that serialize the x field. Each field (in that case x) still have subtype 0 and match the default float implementation
[GhostField(Quantization=700, Smooting=Interpolate)] public float customFloat3.x;
}
```
--------------------------------
### Migrate NetworkStreamDriver Connect/Listen to Singleton
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/upgrade-guide.md
The `Connect` and `Listen` methods, previously accessed via `GetExistingSystem()`, have been moved to the `NetworkStreamDriver` singleton. Users should now call `GetSingletonRW.Connect` and `GetSingletonRW.Listen`.
```C#
// Old way: Accessing Connect/Listen via GetExistingSystem
GetExistingSystem().Connect;
GetExistingSystem().Listen;
// New way: Accessing Connect/Listen via GetSingletonRW
GetSingletonRW.Connect;
GetSingletonRW.Listen;
```
--------------------------------
### ClientServerBootstrap and AutomaticThinClientWorldsUtility API Reference
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/client-server-worlds.md
API reference for the `ClientServerBootstrap` class and `AutomaticThinClientWorldsUtility` in Unity Netcode for Entities, detailing their methods and properties for initializing and creating various types of game worlds (client, server, local simulation, thin-client).
```APIDOC
ClientServerBootstrap:
Initialize(defaultWorldName: string): bool
defaultWorldName: The default name for the world.
Returns: true if initialization is successful.
Description: Initializes the bootstrap process, typically creating game worlds. Can be overridden for custom world creation.
CreateDefaultClientServerWorlds(): void
Description: Creates the default client and server worlds automatically.
CreateClientWorld(): World
Returns: The created client world.
Description: Manually creates a client world.
CreateServerWorld(): World
Returns: The created server world.
Description: Manually creates a server world.
CreateLocalWorld(defaultWorldName: string): void
defaultWorldName: The default name for the local world.
Description: Creates a local simulation world without multiplayer or Netcode systems.
AutomaticThinClientWorldsUtility:
NumThinClientsRequested: int
Description: Sets the number of thin clients to be created.
BootstrapThinClientWorlds(): void
Description: Initiates the creation of thin client worlds based on the 'NumThinClientsRequested' setting.
```
--------------------------------
### Example C# Template for NetCodeSourceGenerator
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/ghost-types-templates.md
This C# code snippet provides an example of a template file used with NetCodeSourceGenerator, specifically adapted from the default `float` template. It illustrates how a `float` value can be quantized and stored within an `int` field inside a `GhostSnapshotData` struct. The template defines methods for predicting delta, serializing, deserializing, copying data to and from snapshots, restoring from backups, and calculating change masks, utilizing `__GHOST_` placeholders for dynamic code generation.
```c#
#templateid: MyCustomNamespace.MyCustomTypeTemplate
#region __GHOST_IMPORTS__
#endregion
namespace Generated
{
public struct GhostSnapshotData
{
struct Snapshot
{
#region __GHOST_FIELD__
public int __GHOST_FIELD_NAME__;
#endregion
}
public void PredictDelta(uint tick, ref GhostSnapshotData baseline1, ref GhostSnapshotData baseline2)
{
var predictor = new GhostDeltaPredictor(tick, this.tick, baseline1.tick, baseline2.tick);
#region __GHOST_PREDICT__
snapshot.__GHOST_FIELD_NAME__ = predictor.PredictInt(snapshot.__GHOST_FIELD_NAME__, baseline1.__GHOST_FIELD_NAME__, baseline2.__GHOST_FIELD_NAME__);
#endregion
}
public void Serialize(int networkId, ref GhostSnapshotData baseline, ref DataStreamWriter writer, StreamCompressionModel compressionModel)
{
#region __GHOST_WRITE__
if ((changeMask & (1 << __GHOST_MASK_INDEX__)) != 0)
writer.WritePackedIntDelta(snapshot.__GHOST_FIELD_NAME__, baseline.__GHOST_FIELD_NAME__, compressionModel);
#endregion
}
public void Deserialize(uint tick, ref GhostSnapshotData baseline, ref DataStreamReader reader,
StreamCompressionModel compressionModel)
{
#region __GHOST_READ__
if ((changeMask & (1 << __GHOST_MASK_INDEX__)) != 0)
snapshot.__GHOST_FIELD_NAME__ = reader.ReadPackedIntDelta(baseline.__GHOST_FIELD_NAME__, compressionModel);
else
snapshot.__GHOST_FIELD_NAME__ = baseline.__GHOST_FIELD_NAME__;
#endregion
}
public unsafe void CopyToSnapshot(ref Snapshot snapshot, ref IComponentData component)
{
if (true)
{
#region __GHOST_COPY_TO_SNAPSHOT__
snapshot.__GHOST_FIELD_NAME__ = (int) math.round(component.__GHOST_FIELD_REFERENCE__ * __GHOST_QUANTIZE_SCALE__);
#endregion
}
}
public unsafe void CopyFromSnapshot(ref Snapshot snapshot, ref IComponentData component)
{
if (true)
{
#region __GHOST_COPY_FROM_SNAPSHOT__
component.__GHOST_FIELD_REFERENCE__ = snapshotBefore.__GHOST_FIELD_NAME__ * __GHOST_DEQUANTIZE_SCALE__;
#endregion
#region __GHOST_COPY_FROM_SNAPSHOT_INTERPOLATE_SETUP__
var __GHOST_FIELD_NAME___Before = snapshotBefore.__GHOST_FIELD_NAME__ * __GHOST_DEQUANTIZE_SCALE__;
var __GHOST_FIELD_NAME___After = snapshotAfter.__GHOST_FIELD_NAME__ * __GHOST_DEQUANTIZE_SCALE__;
#endregion
#region __GHOST_COPY_FROM_SNAPSHOT_INTERPOLATE_DISTSQ__
var __GHOST_FIELD_NAME___DistSq = math.distancesq(__GHOST_FIELD_NAME___Before, __GHOST_FIELD_NAME___After);
#endregion
#region __GHOST_COPY_FROM_SNAPSHOT_INTERPOLATE__
component.__GHOST_FIELD_REFERENCE__ = math.lerp(__GHOST_FIELD_NAME___Before, __GHOST_FIELD_NAME___After, snapshotInterpolationFactor);
#endregion
}
}
public unsafe void RestoreFromBackup(ref IComponentData component, in IComponentData backup)
{
#region __GHOST_RESTORE_FROM_BACKUP__
component.__GHOST_FIELD_REFERENCE__ = backup.__GHOST_FIELD_REFERENCE__;
#endregion
}
public void CalculateChangeMask(ref Snapshot snapshot, ref Snapshot baseline, uint changeMask)
{
#region __GHOST_CALCULATE_CHANGE_MASK_ZERO__
changeMask = (snapshot.__GHOST_FIELD_NAME__ != baseline.__GHOST_FIELD_NAME__) ? 1u : 0;
#endregion
#region __GHOST_CALCULATE_CHANGE_MASK__
changeMask |= (snapshot.__GHOST_FIELD_NAME__ != baseline.__GHOST_FIELD_NAME__) ? (1u<<__GHOST_MASK_INDEX__) : 0;
#endregion
}
#if UNITY_EDITOR || NETCODE_DEBUG
```
--------------------------------
### C# Disable Command Code Generation
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Runtime/SourceGenerators/Source~/Documentation/code-gen-spec.md
This example shows how to prevent the automatic generation of serialization code for an `ICommandData` struct in Unity NetCode by applying the `NetCodeDisableCommandCodeGen` attribute to its definition.
```C#
[NetCodeDisableCommandCodeGen]
public struct NotGenerated : ICommandData
{
public int field1;
public int field2;
..}
```
--------------------------------
### Network Emulator Command Line Arguments
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/playmode-tool.md
Use these command line arguments to load an existing network simulator JSON profile or generate a new default one. If a file path is not specified for generation, 'NetworkSimulatorProfile.json' is used. These arguments enable the simulator profile, defaulting to 'NetworkSimulatorSettings.DefaultSimulatorParameters' if the file is not found or generated. Note that network emulation is only supported in development builds.
```Shell
--loadNetworkSimulatorJsonFile [optionalJsonFilePath]
--createNetworkSimulatorJsonFile [optionalJsonFilePath]
```
--------------------------------
### Get Current Lobby Join Code
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/host-migration/lobby-relay-integration.md
This snippet shows how to retrieve the `LobbyCode` from an existing lobby object. This code can then be displayed in-game for other players to use when joining the lobby.
```C#
var code = lobby.LobbyCode;
```
--------------------------------
### LagCompensationConfig Singleton Component
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/entities-list.md
Provides configuration parameters for the `PhysicsWorldHistory` system, which is responsible for implementing lag compensation on the server. This singleton must exist for the `PhysicsWorldHistory` system to operate.
```APIDOC
LagCompensationConfig:
Description: Configuration for the `PhysicsWorldHistory` system which is used to implement lag compensation on the server. If the singleton does not exist `PhysicsWorldHistory` will no be run.
Type: Singleton Component
```
--------------------------------
### API Reference: Unity.NetCode.IPCAndSocketDriverConstructor
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/networking-network-drivers.md
The default implementation for INetworkStreamDriverConstructor, providing the standard NetworkDriver setup for Netcode for Entities. Its configuration varies based on the world type and PlayMode Tool settings.
```APIDOC
Class: IPCAndSocketDriverConstructor
Description: Default implementation of INetworkStreamDriverConstructor, providing standard NetworkDriver setup.
```
--------------------------------
### Configure GhostAuthoringComponent for Single Baseline Compression
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/optimizations.md
This API documentation describes how to enable single-baseline delta compression for a specific prefab type by setting the `UseSingleBaseline` option within the `GhostAuthoringComponent`. This configuration helps reduce CPU cost for serialization and deserialization, particularly beneficial for components with infrequent changes.
```APIDOC
Class: Unity.NetCode.GhostAuthoringComponent
Property: UseSingleBaseline (bool)
Description: When set to true, instructs the server to always use a single baseline for delta compression for this specific prefab type.
Usage: Configured per-archetype, typically in the Unity Editor or via script, to optimize serialization for specific ghost prefabs.
```
--------------------------------
### API Documentation: ClientTickRate Configuration Parameters
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/time-synchronization.md
Details the parameters available for configuring the ClientTickRate singleton entity in Unity Netcode for Entities, including interpolation buffer, extrapolation limits, and command slack.
```APIDOC
ClientTickRate Parameters:
InterpolationTimeNetTicks: The number of simulation ticks to use as an interpolation buffer for interpolated ghosts.
MaxExtrapolationTimeSimTicks: The maximum time in simulation ticks which the client can extrapolate ahead when data is missing.
MaxPredictAheadTimeMS: The maximum accepted ping. RTT will be clamped to this value when calculating server tick on the client, which means if ping is higher than this the server will get old commands. Increasing this allows the client to deal with higher ping, but the client will run more prediction steps which takes more CPU time.
TargetCommandSlack: Specifies the number of simulation ticks the client tries to make sure the commands are received by the server before they are used on the server.
```
--------------------------------
### API Reference: Unity.NetCode.INetworkStreamDriverConstructor
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/networking-network-drivers.md
An interface that allows for custom configuration and construction of NetworkDriver instances. Implementing this interface enables a custom strategy for driver setup, overriding the default behavior.
```APIDOC
Interface: INetworkStreamDriverConstructor
Description: Defines a contract for custom NetworkDriver setup and construction strategies.
```
--------------------------------
### Unity Netcode: NetworkStreamInGame Host Migration Considerations
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/host-migration/host-migration-considerations.md
Explains the behavior of `NetworkStreamInGame` on the client after a host migration, noting that it might need manual addition. It also introduces `NetworkStreamIsReconnected` for identifying re-connecting clients.
```APIDOC
Unity.NetCode.NetworkStreamInGame:
Description: Represents the state where a connection is in-game and ready to stream ghost snapshots.
Usage in Host Migration:
- On the client, it might need to be added manually after a migration.
- Server creates existing and new connections in-game after subscenes load.
Unity.NetCode.NetworkStreamIsReconnected:
Description: A component added to a connection on the client to indicate it's a re-connection after host migration.
Usage: Check for its presence to differentiate re-connections from new connections.
```
--------------------------------
### C# Example of Original Type Causing Compiler Error
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Runtime/SourceGenerators/Source~/Documentation/code-gen-spec.md
This C# snippet illustrates an `OriginalType` struct marked with `DontSupportPrefabOverridesAttribute`. If a `GhostComponentVariation` is declared for such a type, it will result in a compiler error, as specified in the NetCode rules.
```c#
[DontSupportPrefabOverridesAttribute]
public struct OriginalType : IComponentData
{
}
```
--------------------------------
### Example Custom Component with GhostComponentAttribute
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/ghostcomponentattribute.md
Demonstrates how to apply `GhostComponentAttribute` to a custom component (`MyComponent`) to control its replication behavior, specifically setting `PrefabType`, `SendTypeOptimization`, and `SendDataForChildEntity`. It also shows a `GhostField` for serialization.
```csharp
[GhostComponent(PrefabType=GhostPrefabType.All, SendTypeOptimization=GhostSendType.OnlyInterpolatedClients, SendDataForChildEntity=false)]
public struct MyComponent : IComponentData
{
[GhostField(Quantized=1000)] public float3 Value;
}
```
--------------------------------
### Updated GoInGameServerSystem OnCreate Method (C#)
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/networked-cube.md
This C# code presents the `OnCreate` method for `GoInGameServerSystem`. It ensures the system requires the `CubeSpawner` component and sets up an `EntityQueryBuilder` to process `GoInGameRequest` and `ReceiveRpcCommandRequest` messages. It also initializes a `GetComponentLookup` for `NetworkId`.
```C#
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate();
var builder = new EntityQueryBuilder(Allocator.Temp)
.WithAll()
.WithAll();
state.RequireForUpdate(state.GetEntityQuery(builder));
networkIdFromEntity = state.GetComponentLookup(true);
}
```
--------------------------------
### Enable Host Migration Feature Flag
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/host-migration/host-migration-intro.md
To activate the experimental host migration functionality in Unity Netcode for Entities, the `ENABLE_HOST_MIGRATION` scripting define symbol must be manually added to the project settings.
```APIDOC
ENABLE_HOST_MIGRATION:
Type: Scripting Define Symbol
Location: Player tab, Scripting Define Symbols in Project Settings
Purpose: Enables experimental host migration feature.
```
--------------------------------
### Define an empty RPC Command in C#
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/rpcs.md
To use RPCs in Netcode for Entities, create a command by extending the `IRpcCommand` interface. This example shows a basic, empty RPC command structure that can be used for simple event signaling.
```C#
public struct OurRpcCommand : IRpcCommand
{
}
```
--------------------------------
### Netcode Client Target (NCT) Use-Cases
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/project-settings.md
This table outlines the use-cases for different Netcode Client Target (NCT) settings, determining if a client build supports in-process server hosting. It differentiates between `ClientAndServer` and `ClientOnly` modes and their implications for server creation.
```APIDOC
| NCT | Use-cases |
|-------------------|--------------------------------------------|
| `ClientAndServer` | - You want users to be able to host their own servers (via UI) in the main game executable.
Calling `ClientServerBootstrap.CreateServerWorld` will work. |
| `ClientOnly` | - You only want the server to be hosted by you - the developer.
- You want to ship a DGS (Dedicated Game Server) executable alongside your game executable. Use `ClientOnly` for the game client build and `ClientAndServer` for the DGS build (automatic).
- Your players won't have access to server server hosting functionality.
- Calling `ClientServerBootstrap.CreateServerWorld` throws a NotSupportedException. |
```
--------------------------------
### Disable RPC Serialization Code Generation in C#
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Runtime/SourceGenerators/Source~/Documentation/code-gen-spec.md
This C# example illustrates how to prevent the automatic generation of serialization code for an RPC struct. By applying the NetCodeDisableCommandCodeGen attribute to the struct definition, developers can skip code generation for specific RPCs.
```C#
[NetCodeDisableCommandCodeGen]
public struct NoCodeGenerateRpc : IRpcCommand
{
public int field1;
public int field2;
..
}
```
--------------------------------
### NetworkStreamDriver API for Manual Connection Control
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Documentation~/network-connection.md
The NetworkStreamDriver is a singleton available in both client and server worlds, providing methods to manually initiate network connections or start listening for incoming connections. It's essential for custom connection workflows.
```APIDOC
NetworkStreamDriver:
Connect(endpoint: NetworkEndpoint)
Description: Initiates a connection to the specified network endpoint.
Parameters:
endpoint: NetworkEndpoint - The target address and port for the connection.
Listen(endpoint: NetworkEndpoint)
Description: Starts listening for incoming connections on the specified network endpoint.
Parameters:
endpoint: NetworkEndpoint - The local address and port to bind to for listening.
```
--------------------------------
### C# GhostComponentVariation with GhostComponent and GhostField Attributes
Source: https://github.com/needle-mirror/com.unity.netcode/blob/master/Runtime/SourceGenerators/Source~/Documentation/code-gen-spec.md
This C# example demonstrates the declaration of a `GhostComponentVariation` struct. It shows how to associate the variant with an `ORIGINAL_TYPE` using `GhostComponentVariationAttribute` and how to apply the `GhostComponentAttribute`. Individual fields are marked for serialization using `GhostFieldAttribute`, including quantization options.
```c#
//GhostComponentVariation permit to use the GhostComponent attribute
[GhostComponentVariation(typeof(ORIGINAL_TYPE))]
[GhostComponent(...)]
struct MySerializationVariant
{
[GhostField] public int FieldA;
[GhostField] public int FieldB;
[GhostField(Quantization=1000)] public float FieldB;
...
}
```