### Utility Function: Migrate Data to New Server World (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/host-migration/host-migration-systems This static utility function, MigrateDataToNewServerWorld, is responsible for setting up a new server world with provided migration data and starting network listeners. It handles driver setup, world creation, data migration, and client connection configuration. It assumes the existence of ClientServerBootstrap and NetworkStreamReceiveSystem. ```csharp public static bool MigrateDataToNewServerWorld(INetworkStreamDriverConstructor driverConstructor, ref NativeArray migrationData) { var oldConstructor = NetworkStreamReceiveSystem.DriverConstructor; NetworkStreamReceiveSystem.DriverConstructor = driverConstructor; var serverWorld = ClientServerBootstrap.CreateServerWorld("ServerWorld"); NetworkStreamReceiveSystem.DriverConstructor = oldConstructor; if (migrationData.Length == 0) Debug.LogWarning($"No host migration data given during host migration, no data will be deployed."); else HostMigrationUtility.SetHostMigrationData(serverWorld, migrationData); using var serverDriverQuery = serverWorld.EntityManager.CreateEntityQuery(ComponentType.ReadWrite()); var serverDriver = serverDriverQuery.GetSingletonRW(); if (!serverDriver.ValueRW.Listen(NetworkEndpoint.AnyIpv4)) { Debug.LogError($"NetworkStreamDriver.Listen() failed"); return false; } var ipcPort = serverDriver.ValueRW.GetLocalEndPoint(serverDriver.ValueRW.DriverStore.FirstDriver).Port; // The client driver needs to be recreated, and then directly connected to new server world via IPC return ConfigureClientAndConnect(ClientServerBootstrap.ClientWorld, driverConstructor, NetworkEndpoint.LoopbackIpv4.WithPort(ipcPort)); } ``` -------------------------------- ### GetHash API Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.Hybrid Gets the hash of the Baking System settings asset. ```APIDOC ## GET /websites/unity3d_packages_com_unity_netcode_1_9/SettingsHash ### Description Gets the hash of the settings asset. ### Method GET ### Endpoint /websites/unity3d_packages_com_unity_netcode_1_9/SettingsHash ### Parameters No parameters available. ### Request Example ```json { "example": "No request body needed for this GET request." } ``` ### Response #### Success Response (200) - **Hash128** (string) - Returns the hash as a Hash128 value. #### Response Example ```json { "example": ""0x1234567890abcdef1234567890abcdef"" } ``` ``` -------------------------------- ### Custom Client Physics World Setup (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/physics Sets up a secondary physics world group for client-side simulation, allowing for independent physics calculations. The constructor takes a world index and a boolean to determine if static colliders should be shared with the main physics world. ```csharp [WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation)] [UpdateInGroup(typeof(FixedStepSimulationSystemGroup))] public partial class VisualizationPhysicsSystemGroup : CustomPhysicsSystemGroup { //This should match the value you set into the `Client Non Ghost World` property. public const int WorldToSimulate = 1; public VisualizationPhysicsSystemGroup() : base(WorldToSimulate, true) { protected override void OnCreate() { base.OnCreate(); //Any other things you need. } } } ``` -------------------------------- ### Unity Netcode: Server Connection Approval Setup (C#) Source: https://context7.com/context7/unity3d_packages_com_unity_netcode_1_9/llms.txt This C# code sets up the server-side to require connection approval in Unity Netcode. It configures the NetworkStreamDriver to demand approval and starts listening on a specified port. This is the initial step for implementing a secure connection process on the server. ```csharp // Enable approval on server [WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)] public partial class ServerSetupApprovalSystem : SystemBase { private bool approvalEnabled = false; protected override void OnUpdate() { if (!approvalEnabled) { var driverQuery = EntityManager.CreateEntityQuery( ComponentType.ReadWrite()); var driver = driverQuery.GetSingletonRW(); driver.ValueRW.RequireConnectionApproval = true; var endpoint = NetworkEndpoint.AnyIpv4.WithPort(7979); driver.ValueRW.Listen(endpoint); approvalEnabled = true; driverQuery.Dispose(); } } } ``` -------------------------------- ### Force Physics Initialization for Multi-Physics Worlds Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/physics This C# code forces a single update of the physics system to ensure necessary components are initialized, even when not connected or when dealing with predicted ghosts. It's part of a multi-physics world setup that allows physics to run before ghost data is received, ensuring the custom physics world updates at a fixed rate on the client. ```csharp using Unity.Entities; using Unity.Physics; using Unity.Physics.Systems; using Unity.Core; public partial class ForcePhysicsInitializationIfNotConnect : SystemBase { protected override void OnUpdate() { if (SystemAPI.GetSingleton().Type == SimulationType.NoPhysics) { //Force a single update of physics just to ensure we have some stuff setup World.PushTime(new TimeData(0.0, 0f)); World.GetExistingSystem().Update(World.Unmanaged); World.PopTime(); Enabled = false; } } } ``` -------------------------------- ### Unity Netcode: Auto-Connect Client-Server Bootstrap Source: https://context7.com/context7/unity3d_packages_com_unity_netcode_1_9/llms.txt This C# code demonstrates a custom bootstrap for Unity Netcode that enables automatic connection on a specified port. It initializes both client and server worlds based on the build configuration, simplifying the connection setup process. ```csharp using Unity.Entities; using Unity.NetCode; using Unity.Networking.Transport; // Custom bootstrap with auto-connect public class GameBootstrap : ClientServerBootstrap { public override bool Initialize(string defaultWorldName) { // Enable auto-connect on port 7979 AutoConnectPort = 7979; // Create client and server worlds based on build configuration CreateDefaultClientServerWorlds(); return true; } } ``` -------------------------------- ### Replacing Static RpcSystem.DynamicAssemblyList (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/upgrade-guide This example shows the migration from the static `RpcSystem.DynamicAssemblyList` to an instance-based property. This change requires instantiating `RpcSystem` during world creation and before its `OnUpdate` method is called. Refer to NetcodeSamples for a complete implementation. ```csharp using Unity.Netcode; // Ensure RpcSystem is instantiated before OnUpdate is called. // Example of using the instance property: var rpcSystem = World.GetOrCreateSystemManaged(); rpcSystem.DynamicAssemblyList.Add(typeof(MyCustomRpcComponent)); ``` -------------------------------- ### GhostAuthoringInspectionComponent Enhancements Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/changelog/CHANGELOG The `GhostAuthoringInspectionComponent` now provides more detailed information regarding default variant selection. This aids in debugging and understanding component setup. ```csharp `GhostAuthoringInspectionComponent` now provides more information about default variant selection. ``` -------------------------------- ### Manually Creating Netcode Worlds in Unity Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/client-server-worlds Provides examples of manually creating different types of Netcode worlds (client, server, thin client, default client/server) and triggering thin client bootstrapping. This is useful when customizing the bootstrapping flow or when integrating with UI elements like buttons. ```csharp void OnPlayButtonClicked() { // Typically this: var clientWorld = ClientServerBootstrap.CreateClientWorld(); // And/Or this: var serverWorld = ClientServerBootstrap.CreateServerWorld(); // And/Or something like this, for soak testing: AutomaticThinClientWorldsUtility.NumThinClientsRequested = 10; AutomaticThinClientWorldsUtility.BootstrapThinClientWorlds(); // Or the following, which creates worlds smartly based on: // - The Playmode Tool setting specified in the editor. // - The current build type, if used in a player. ClientServerBootstrap.CreateDefaultClientServerWorlds(); } ``` -------------------------------- ### Cube Input Authoring and Baking Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/networked-cube Provides the `CubeInputAuthoring` MonoBehaviour and its associated `CubeInputBaking` baker. This setup allows the `CubeInput` component to be added to entities during the baking process in Unity's DOTS. ```csharp [DisallowMultipleComponent] public class CubeInputAuthoring : MonoBehaviour { class CubeInputBaking : Unity.Entities.Baker { public override void Bake(CubeInputAuthoring authoring) { var entity = GetEntity(TransformUsageFlags.Dynamic); AddComponent(entity); } } } ``` -------------------------------- ### PhysicsDefaultVariantSystem for PhysicVelocity Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/changelog/CHANGELOG Adds `PhysicsDefaultVariantSystem`, which optionally sets the default variant for `PhysicVelocity` if a user-defined default is not supplied. This streamlines physics simulation setup. ```csharp A `PhysicsDefaultVariantSystem` that optionally setup the default variant to use for `PhysicVelocity` if a user defined default is not provided. ``` -------------------------------- ### Unity Netcode: Setup Client World with NetworkStreamDriverReset Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/networking-using-relay This C# function sets up the client world for Unity Netcode, including the initialization and resetting of the NetworkStreamDriver. It assumes the use of Relay and configures client UDP settings accordingly. The driver store is reset after driver registration. ```csharp 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); } ``` -------------------------------- ### Unity Netcode: Auto-Connect Bootstrap Configuration (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/networked-cube This C# code defines a custom bootstrap class for Unity Netcode for Entities, enabling the auto-connect feature. It inherits from ClientServerBootstrap and sets a specific port for automatic connections. This is essential for simplifying client-server communication setup in games. ```csharp using System; using Unity.Entities; using Unity.NetCode; // Create a custom bootstrap, which enables auto-connect. // The bootstrap can also be used to configure other settings as well as to // manually decide which worlds (client and server) to create based on user input [UnityEngine.Scripting.Preserve] public class GameBootstrap : ClientServerBootstrap { public override bool Initialize(string defaultWorldName) { AutoConnectPort = 7979; // Enabled auto connect return base.Initialize(defaultWorldName); // Use the regular bootstrap } } ``` -------------------------------- ### Custom Ghost Classification System Example Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity Demonstrates how to define a custom system for classifying spawned ghosts by updating within the GhostSpawnClassificationSystemGroup. This allows for custom logic in handling newly spawned network entities. ```csharp [UpdateInGroup(typeof(GhostSpawnClassificationSystemGroup))] public partial struct MyCustomClassificationSystemGroup { // ... custom classification logic ... } ``` -------------------------------- ### Create and Replicate Ghost Entities in Unity Netcode Source: https://context7.com/context7/unity3d_packages_com_unity_netcode_1_9/llms.txt Demonstrates how to define a replicated component (PlayerComponent) with serialized fields using [GhostField] and how server-side instantiation of entities leads to automatic replication to clients. Includes example systems for spawning on the server and reading on the client. ```csharp using Unity.Entities; using Unity.NetCode; using Unity.Mathematics; // Define a replicated component with serialized fields public struct PlayerComponent : IComponentData { [GhostField] public int Health; [GhostField(Quantization=1000)] public float Speed; [GhostField(Quantization=1000, Smoothing=SmoothingAction.Interpolate)] public float3 Position; public float NonReplicatedValue; // Not marked with GhostField, won't replicate } // Server spawns ghost - automatically replicated to all clients [WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)] public partial class SpawnPlayerSystem : SystemBase { protected override void OnUpdate() { // Get the player prefab entity var playerPrefab = GetPlayerPrefabEntity(); // Instantiate creates a ghost that will be replicated var playerEntity = EntityManager.Instantiate(playerPrefab); // Set initial data EntityManager.SetComponentData(playerEntity, new PlayerComponent { Health = 100, Speed = 5.0f, Position = new float3(0, 0, 0) }); } } // Client receives ghost automatically and can read its data [WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation)] public partial class ReadPlayerSystem : SystemBase { protected override void OnUpdate() { Entities.ForEach((in PlayerComponent player, in GhostInstance ghost) => { // Access replicated data on client UnityEngine.Debug.Log($"Player Health: {player.Health}, Position: {player.Position}"); }).Schedule(); } } ``` -------------------------------- ### Download Host Migration Data in C# Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/host-migration/lobby-relay-integration Downloads host migration data as the new host by obtaining the migration data info and passing it to the DownloadMigrationDataAsync function. This executes an HTTP GET request using UnityWebRequest. ```csharp byte[] data = await LobbyService.Instance.DownloadMigrationDataAsync(info); ``` -------------------------------- ### Implement RPCs with IRpcCommand Interface Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/changelog/CHANGELOG This example shows how to create RPCs without manual serialization by implementing the `IRpcCommand` interface. The serialization code for the RPC is automatically generated, simplifying the process and allowing RPCs to be written like regular `IComponentData`. ```csharp using Unity.Netcode; using Unity.Netcode.Serialization; public struct MyRpcParams : IRpcCommandParams { public int PlayerId; public void Serialize(FastBufferWriter writer) { writer.WriteValue(PlayerId); } public void Deserialize(FastBufferReader reader) { reader.ReadValue(out PlayerId); } public static MyRpcParams Create(int playerId) { return new MyRpcParams { PlayerId = playerId }; } } // Example usage within a NetworkBehaviour public class MyNetworkBehaviour : NetworkBehaviour { public void SendMyRpc(int playerId) { CustomMessagingManager.SendNamedMessage("MyRpc", MyRpcParams.Create(playerId)); } [RegisterNamedMessage("MyRpc")] public static void HandleMyRpc(int clientId, FastBufferReader reader) { var rpcParams = new MyRpcParams(); rpcParams.Deserialize(reader); // Process RPC with rpcParams.PlayerId } } ``` -------------------------------- ### Get and Upload Host Migration Data (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/host-migration/host-migration-systems This code retrieves host migration data when it's updated and uploads it to the lobby service. It uses HostMigrationStats and LobbyService.Instance.UploadMigrationDataAsync. Ensure HostMigrationStats singleton component is available and m_MigrationConfig is initialized. ```csharp var uploadData = new NativeList(Allocator.Temp); if (SystemAPI.TryGetSingleton(out var stats) && stats.LastDataUpdateTime > m_LastUpdateTime) { HostMigration.GetHostMigrationData(ref uploadData); var uploadArray = uploadData.AsArray().ToArray(); LobbyService.Instance.UploadMigrationDataAsync(m_MigrationConfig, uploadArray, new LobbyUploadMigrationDataOptions()); } ``` -------------------------------- ### Replace Static RpcSystem Calls with Instanced Properties Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/changelog/CHANGELOG Calls to the static `RpcSystem.DynamicAssemblyList` should be replaced with instanced calls to the property with the same name. This ensures proper management of RPC systems during world creation before `RpcSystem.OnUpdate` is invoked. The `SetRpcSystemDynamicAssemblyListSystem` provides an example of this migration. ```csharp using Unity.Netcode.Rpc; // Old code: // RpcSystem.DynamicAssemblyList.Add(typeof(MyRpcSystem)); // New code (during world creation): // World.GetOrCreateSystem().DynamicAssemblyList.Add(typeof(MyRpcSystem)); ``` -------------------------------- ### Listen for Client Connection Events in Unity Netcode Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/network-connection This example demonstrates how to listen for client connection events using the NetworkStreamDriver's ConnectionEventsForTick collection. It iterates through the events and logs them, allowing you to react to client connection and disconnection events within your systems. Requires access to the NetworkStreamDriver singleton. ```C# // 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()}!"); } } } ``` -------------------------------- ### Unity Netcode: Server Listen System Source: https://context7.com/context7/unity3d_packages_com_unity_netcode_1_9/llms.txt This C# system configures the server in Unity Netcode to listen for incoming client connections on a specified port using NetworkStreamRequestListen. It ensures the server is ready to accept connections once initiated, making it a fundamental part of the server-side setup. ```csharp using Unity.Entities; using Unity.NetCode; using Unity.Networking.Transport; // Server starts listening [WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)] public partial class ServerListenSystem : SystemBase { private bool isListening = false; protected override void OnUpdate() { if (!isListening) { var listenEndpoint = NetworkEndpoint.AnyIpv4.WithPort(7979); var listenRequest = EntityManager.CreateEntity( typeof(NetworkStreamRequestListen)); EntityManager.SetComponentData(listenRequest, new NetworkStreamRequestListen { Endpoint = listenEndpoint }); isListening = true; } } } ``` -------------------------------- ### Configure Ghost Replication in Unity Netcode Source: https://context7.com/context7/unity3d_packages_com_unity_netcode_1_9/llms.txt Shows how to configure ghost replication using attributes like [GhostComponent] and [GhostField] for different data types, including private data, enabled components, and replicated buffers. Includes an example system demonstrating server-side modification and replication. ```csharp using Unity.Entities; using Unity.NetCode; // Component only present on server and owner client [GhostComponent(PrefabType = GhostPrefabType.Server | GhostPrefabType.Client, OwnerSendType = SendToOwnerType.SendToOwner)] public struct PrivatePlayerData : IComponentData { [GhostField] public int SecretScore; } // Component with enabled bit replication [GhostComponent] [GhostEnabledBit] public struct PowerUpActive : IComponentData, IEnableableComponent { [GhostField] public float Duration; } // Replicated buffer public struct InventoryItem : IBufferElementData { [GhostField] public int ItemId; [GhostField] public int Quantity; } // System to use these components [WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)] public partial class PlayerDataSystem : SystemBase { protected override void OnUpdate() { Entities.ForEach((Entity entity, ref PrivatePlayerData privateData, DynamicBuffer inventory) => { privateData.SecretScore += 10; // Add item to buffer inventory.Add(new InventoryItem { ItemId = 5, Quantity = 1 }); // Enable component (enabled bit will be replicated) SetComponentEnabled(entity, true); }).Schedule(); } } ``` -------------------------------- ### Integrating Debugger Launch in NetcodeSourceGenerator Execute Method Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/source-generators This example shows how to integrate the `Debug.LaunchDebugger()` call within the `Execute` method of the `NetcodeSourceGenerator`. It suggests placing the debugger launch call before the main generation logic to ensure the debugger is attached when needed. A note is included about potential multiple debugger pop-ups if assembly filtering is not used. ```csharp public void Execute(GeneratorExecutionContext executionContext) { .... Debug.LaunchDebugger(); try { Generate(executionContext, diagnostic); } catch (Exception e) { ... ``` -------------------------------- ### Unity Netcode: Setup Server World with NetworkStreamDriverReset Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/networking-using-relay This C# function configures the server world for Unity Netcode, enabling both IPC and UDP drivers with Relay support. It demonstrates how to reset the NetworkStreamDriver store after registering multiple server drivers. The code includes conditional compilation for WebSocket driver registration. ```csharp 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); } ``` -------------------------------- ### Deploy Host Migration Data to New Server (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/host-migration/host-migration-systems This snippet shows how a client downloads host migration data and deploys it to a newly created server world. It involves using LobbyService.Instance.DownloadMigrationDataAsync, RelayService.Instance.CreateAllocationAsync, and HostMigration.MigrateDataToNewServerWorld. Requires initialized m_MigrationConfig. ```csharp 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"); } ``` -------------------------------- ### NetCodeClientSettings Class Overview Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.Hybrid Provides an overview of the NetCodeClientSettings class, its inheritance, interfaces, and members. ```APIDOC ## Class NetCodeClientSettings The Unity.Entities.Build.IEntitiesPlayerSettings baking settings to use for client only builds. You can assign the GUID to the BuildConfigurationGUID to instrument the asset import worker to bake the scene using this setting. ### Inheritance - object - ScriptableObject - ScriptableSingleton - NetCodeClientSettings ### Implements - IEntitiesPlayerSettings ### Namespace Unity.NetCode.Hybrid ### Assembly Unity.NetCode.Authoring.Hybrid.dll ### Syntax ```csharp [FilePath("ProjectSettings/NetCodeClientSettings.asset", FilePathAttribute.Location.ProjectFolder)] public class NetCodeClientSettings : ScriptableSingleton, IEntitiesPlayerSettings ``` ## Fields ### ClientTarget - **Declaration** ```csharp [SerializeField] public NetCodeClientTarget ClientTarget ``` - **Field Value** | Type | Description | |---|---| | NetCodeClientTarget | | ## Properties ### CustomDependency - **Description**: The custom dependency key. - **Declaration** ```csharp public string CustomDependency { get; } ``` - **Property Value** | Type | Description | |---|---| | string | | ### GUID - **Description**: The unique ID of the settings asset. - **Declaration** ```csharp public Hash128 GUID { get; } ``` - **Property Value** | Type | Description | |---|---| | Hash128 | | ## Methods ### GetAdditionalScriptingDefines() - **Description**: Gets the set of scripting defines applied while building the player. - **Declaration** ```csharp public string[] GetAdditionalScriptingDefines() ``` - **Returns** | Type | Description | |---|---| | string[] | Returns the array of scripting defines. | ### GetFilterSettings() - **Description**: Gets the list of assemblies to be excluded during baking. - **Declaration** ```csharp public string[] GetFilterSettings() ``` ``` -------------------------------- ### GUID Property Declaration (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.Hybrid Defines the read-only GUID property for NetCodeClientSettings. This property returns the unique Hash128 identifier for the settings asset. ```csharp public Hash128 GUID { get; } ``` -------------------------------- ### Accessing Netcode APIs via Singletons (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/upgrade-guide This snippet demonstrates how to access Netcode logging, network stream driver, ghost simulation, and relevancy APIs using the new singleton pattern. It replaces older methods of accessing existing systems. Ensure the relevant Netcode packages are included in your project. ```csharp using Unity.Netcode; using Unity.Netcode.Components; using Unity.Netcode.Transport; // Replace GetExistingSystem().NetDebug var netDebug = GetSingleton(); // Replace GetExistingSystem().Connect GetSingletonRW().Connect("127.0.0.1", 7777); // Replace GetExistingSystem().SpawnedGhostEntityMap var spawnedGhostMap = GetSingleton().Value; // Replace GetExistingSystem().GhostRelevancySet var ghostRelevancy = GetSingletonRW(); var relevancySet = ghostRelevancy.GhostRelevancySet; var relevancyMode = ghostRelevancy.GhostRelevancyMode; ``` -------------------------------- ### Default Client/Server World Initialization in Netcode for Entities Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/client-server-worlds Demonstrates the default `Initialize` method of `ClientServerBootstrap` which automatically creates the client and server worlds at runtime. This is part of the Netcode for Entities package in Unity. ```csharp public class ClientServerBootstrap { public virtual bool Initialize(string defaultWorldName) { CreateDefaultClientServerWorlds(); return true; } } ``` -------------------------------- ### Client Connection Approval Logic - Unity Netcode Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/network-connection This C# system handles the client-side logic for connection approval. It queries for connections that haven't fully connected and haven't started the approval process. When found, it creates and sends an `ApprovalFlow` RPC, marking the connection as having started the approval process to prevent repeated attempts. ```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); } } ``` -------------------------------- ### OnCreate Method for PrespawnedGhostPreprocessScene (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.Editor This method is part of the ISystem interface and is called when the system is created. It is decorated with BurstCompile for performance optimization and takes a reference to the SystemState as a parameter. ```csharp [BurstCompile] public void OnCreate(ref SystemState state) ``` -------------------------------- ### EndPredictedSimulationEntityCommandBufferSystem.Singleton Methods Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.EndPredictedSimulationEntityCommandBufferSystem This section details the methods available for the EndPredictedSimulationEntityCommandBufferSystem.Singleton struct, including creating command buffers and setting allocators. ```APIDOC ## Struct EndPredictedSimulationEntityCommandBufferSystem.Singleton ### Description Represents a singleton component for the EndPredictedSimulationEntityCommandBufferSystem. ### Namespace Unity.NetCode ### Assembly Unity.NetCode.dll ### Methods #### CreateCommandBuffer(WorldUnmanaged) ##### Description Creates an EntityCommandBuffer for the specified world. ##### Method `public EntityCommandBuffer CreateCommandBuffer(WorldUnmanaged world)` ##### Parameters - **world** (WorldUnmanaged) - The unmanaged world to create the command buffer for. ##### Returns - **EntityCommandBuffer** - The created entity command buffer. #### SetAllocator(Allocator) ##### Description Sets the allocator for the command buffer system. ##### Method `public void SetAllocator(Allocator allocatorIn)` ##### Parameters - **allocatorIn** (Allocator) - The allocator to use. #### SetAllocator(AllocatorHandle) ##### Description Sets the allocator for the command buffer system using an AllocatorHandle. ##### Method `public void SetAllocator(AllocatorManager.AllocatorHandle allocatorIn)` ##### Parameters - **allocatorIn** (AllocatorManager.AllocatorHandle) - The allocator handle to use. #### SetPendingBufferList(ref UnsafeList) ##### Description Sets the list of pending buffers for the command buffer system. ##### Method `public void SetPendingBufferList(ref UnsafeList buffers)` ##### Parameters - **buffers** (ref UnsafeList) - A reference to the list of entity command buffers. ``` -------------------------------- ### Customizing Netcode for Entities Bootstrapping Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/client-server-worlds Shows how to override the default `Initialize` method in a custom bootstrap class (`MyGameSpecificBootstrap`) to create only a local simulation world, preventing automatic client and server world creation. This allows for more control over world initialization in specific game flows. ```csharp 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; } } ``` -------------------------------- ### Enable Host Migration Systems in Server World (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/host-migration/host-migration-systems This snippet demonstrates how to enable host migration by creating an EnableHostMigration singleton component in the server world using Netcode for Entities. It requires access to ClientServerBootstrap and EntityManager. ```csharp var serverWorld = ClientServerBootstrap.ServerWorld; serverWorld.EntityManager.CreateEntity(ComponentType.ReadOnly()); ``` -------------------------------- ### Unity Netcode: ReceiveJobData Fields - snapshotAckType Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.CommandReceiveSystem-2 Type handle to get the NetworkSnapshotAck for the connection, used for acknowledging network snapshots in Unity Netcode. ```csharp public ComponentTypeHandle snapshotAckType ``` -------------------------------- ### Get NetworkTime Singleton Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/intro-to-prediction Retrieves the `NetworkTime` singleton to access network timing information such as tick prediction status. This is crucial for understanding the current state of network synchronization. ```csharp var networkTime = SystemAPI.GetSingleton(); ``` -------------------------------- ### Delegate: ThinClientWorldInitializationDelegate Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.AutomaticThinClientWorldsUtility Details for the AutomaticThinClientWorldsUtility.ThinClientWorldInitializationDelegate, used for initializing thin client worlds in Unity Netcode. ```APIDOC ## Delegate: AutomaticThinClientWorldsUtility.ThinClientWorldInitializationDelegate ### Description Delegate for `DefaultBootstrapThinClientWorldInitialization(World)` and `DefaultRuntimeThinClientWorldInitialization(World)`. ### Namespace Unity.NetCode ### Assembly Unity.NetCode.dll ### Syntax ```csharp public delegate World AutomaticThinClientWorldsUtility.ThinClientWorldInitializationDelegate(World referenceWorld) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters | Type | Name | Description | |---|---|---| | World | referenceWorld | The world to reference when creating this one (for the purposes of scene loading etc.). | ### Request Example ```json { "example": "No request body example available for delegate" } ``` ### Response #### Success Response (200) | Type | Description | |---|---| | World | The newly created world, otherwise null. | #### Response Example ```json { "example": "No response body example available for delegate" } ``` ``` -------------------------------- ### TransformDefaultVariantSystem for LocalTransform Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/changelog/CHANGELOG Introduces `TransformDefaultVariantSystem`, which optionally sets the default variant for `LocalTransform` (specifically `Rotation` and `Position` for V1) if a user-defined default is not provided. This simplifies transform setup. ```csharp A `TransformDefaultVariantSystem` that optionally setup the default variant to use for `LocalTransform`, (`Rotation`, `Position` for V1) if a user defined default is not provided. ``` -------------------------------- ### OnCreate Method Implementation (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode This C# code shows the implementation of the OnCreate method for the WarnAboutStaleRpcSystem. Marked with BurstCompile, this method is called when the system is created and is responsible for initializing the system's state. It takes a reference to the SystemState as a parameter. ```csharp [BurstCompile] public void OnCreate(ref SystemState state) { } ``` -------------------------------- ### BeginPredictedSimulationEntityCommandBufferSystem.Singleton Methods Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.BeginPredictedSimulationEntityCommandBufferSystem This section details the methods available for the BeginPredictedSimulationEntityCommandBufferSystem.Singleton struct, including CreateCommandBuffer, SetAllocator, and SetPendingBufferList. ```APIDOC ## Struct BeginPredictedSimulationEntityCommandBufferSystem.Singleton ### Description Represents a singleton component for the BeginPredictedSimulationEntityCommandBufferSystem. ### Namespace Unity.NetCode ### Assembly Unity.NetCode.dll ### Methods #### CreateCommandBuffer(WorldUnmanaged) Creates an EntityCommandBuffer for the given unmanaged world. - **Method**: `public EntityCommandBuffer CreateCommandBuffer(WorldUnmanaged world)` - **Parameters**: - `world` (WorldUnmanaged) - The unmanaged world to create the command buffer for. - **Returns**: - `EntityCommandBuffer` - The created entity command buffer. #### SetAllocator(Allocator) Sets the allocator for the command buffer system. - **Method**: `public void SetAllocator(Allocator allocatorIn)` - **Parameters**: - `allocatorIn` (Allocator) - The allocator to use. #### SetAllocator(AllocatorHandle) Sets the allocator for the command buffer system using an AllocatorHandle. - **Method**: `public void SetAllocator(AllocatorManager.AllocatorHandle allocatorIn)` - **Parameters**: - `allocatorIn` (AllocatorManager.AllocatorHandle) - The allocator handle to use. #### SetPendingBufferList(ref UnsafeList) Sets the list of pending entity command buffers. - **Method**: `public void SetPendingBufferList(ref UnsafeList buffers)` - **Parameters**: - `buffers` (ref UnsafeList) - A reference to the list of entity command buffers. ### Implements - IComponentData - IQueryTypeParameter - IECBSingleton ``` -------------------------------- ### Get Filter Settings in Unity Netcode Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.Hybrid Retrieves the serialized BakingSystemFilterSettings. This method is part of the IEntitiesPlayerSettings interface in Unity Netcode and returns an object containing filter configurations. ```csharp public BakingSystemFilterSettings GetFilterSettings() { // Implementation details would go here return new BakingSystemFilterSettings(); } ``` -------------------------------- ### Declare an RPC using IRpcCommand (C#) Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity Example of declaring an RPC struct that implements the IRpcCommand interface. This allows for automatic generation of serialization and request handling code. ```csharp public struct MyRpc : IRpcCommand { public int SomeData; } ``` -------------------------------- ### Create Entity Command Buffer with NetworkGroupCommandBufferSystem.Singleton Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.NetworkGroupCommandBufferSystem Demonstrates how to obtain the `NetworkGroupCommandBufferSystem.Singleton` and use its `CreateCommandBuffer` method to generate an Entity Command Buffer (ECB). This ECB can then be used to record entity commands that will be played back by the associated system. The `world` parameter specifies the unmanaged world context for playback. ```csharp using Unity.NetCode; using Unity.Entities; // ... within a system or relevant scope // Get the singleton instance of the NetworkGroupCommandBufferSystem var commandBufferSystemSingleton = World.DefaultGameObjectInjectionWorld.GetExistingSystem().GetSingleton(); // Create a command buffer to record commands EntityCommandBuffer commandBuffer = commandBufferSystemSingleton.CreateCommandBuffer(World.DefaultGameObjectInjectionWorld.Unmanaged); // Use the commandBuffer to record entity commands... // For example: // commandBuffer.AddComponent(entity); // The command buffer will be automatically added to the system's pending list for playback. ``` -------------------------------- ### Component Serialization Example - C# Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/ghostfield-synchronize Illustrates how to apply `GhostFieldAttribute` to individual fields within an `IComponentData` struct to control serialization and replication. Fields without the attribute are not serialized. ```csharp public struct MySerializedComponent : IComponentData { [GhostField]public int MyIntField; [GhostField(Quantization=1000)]public float MyFloatField; [GhostField(Quantization=1000, Smoothing=SmoothingAction.Interpolate)]public float2 Position; public float2 NonSerializedField; ... } ``` -------------------------------- ### Server System: GoInGameServerSystem for Unity Netcode Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/networked-cube The GoInGameServerSystem operates on the server to handle client requests to join the game. It requires CubeSpawner and incoming GoInGameRequest RPCs. Upon receiving a request, it associates the client with NetworkStreamInGame, logs the connection, instantiates a player prefab, assigns ownership, and adds the player to a linked entity group for proper cleanup. ```csharp // When server receives go in game request, go in game and delete request [BurstCompile] [WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)] public partial struct GoInGameServerSystem : ISystem { private ComponentLookup networkIdFromEntity; [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); } [BurstCompile] public void OnUpdate(ref SystemState state) { // Get the prefab to instantiate var prefab = SystemAPI.GetSingleton().Cube; // Ge the name of the prefab being instantiated state.EntityManager.GetName(prefab, out var prefabName); var worldName = new FixedString32Bytes(state.WorldUnmanaged.Name); var commandBuffer = new EntityCommandBuffer(Allocator.Temp); networkIdFromEntity.Update(ref state); foreach (var (reqSrc, reqEntity) in SystemAPI.Query>().WithAll().WithEntityAccess()) { commandBuffer.AddComponent(reqSrc.ValueRO.SourceConnection); // Get the NetworkId for the requesting client var networkId = networkIdFromEntity[reqSrc.ValueRO.SourceConnection]; // Log information about the connection request that includes the client's assigned NetworkId and the name of the prefab spawned. UnityEngine.Debug.Log($"'{worldName}' setting connection '{networkId.Value}' to in game, spawning a Ghost '{prefabName}' for them!"); // Instantiate the prefab var player = commandBuffer.Instantiate(prefab); // Associate the instantiated prefab with the connected client's assigned NetworkId commandBuffer.SetComponent(player, new GhostOwner { NetworkId = networkId.Value}); // Add the player to the linked entity group so it is destroyed automatically on disconnect commandBuffer.AppendToBuffer(reqSrc.ValueRO.SourceConnection, new LinkedEntityGroup{Value = player}); commandBuffer.DestroyEntity(reqEntity); } commandBuffer.Playback(state.EntityManager); } } ``` -------------------------------- ### GhostField Inheritance Example - C# Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/ghostfield-synchronize Demonstrates how `GhostFieldAttribute` properties, like quantization, are inherited by subfields of non-primitive types when not explicitly defined on the subfield. This allows for concise serialization configurations. ```csharp public struct Vector2 { public float x; [GhostField(Quantization=100)] public float y; } public struct MyComponent : IComponentData { //Value.x will inherit the quantization value specified by the parent definition (1000). //Value.y will maintain its original quantization value (100). [GhostField(Quantized=1000)] public Vector2 Value; } ``` -------------------------------- ### Unity Netcode: ReceiveJobData Fields - networkIdType Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.CommandReceiveSystem-2 A read-only type handle to get the NetworkId for the connection, used for identifying network entities in Unity's Netcode system. ```csharp [ReadOnly] public ComponentTypeHandle networkIdType ``` -------------------------------- ### Get Hash of Settings Asset in Unity Netcode Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.Hybrid Calculates and returns a Hash128 value representing the hash of the settings asset. This is useful for detecting changes in configuration. Implements the IEntitiesPlayerSettings interface. ```csharp public Hash128 GetHash() { // Implementation details to calculate hash would go here return new Hash128(); } ``` -------------------------------- ### SetRpcSystemDynamicAssemblyListSystem in GoInGame.cs Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/networked-cube This system, defined in GoInGame.cs, enables dynamic assembly list for RPCs, facilitating communication between standalone builds and the editor for testing. It's configured to run across client, server, and thin client simulations and is dependent on RpcSystem. ```csharp 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; } } ``` -------------------------------- ### Define Thin Client World Initialization Delegate - C# Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/api/Unity.NetCode.AutomaticThinClientWorldsUtility Defines a delegate for initializing thin client worlds. This delegate is used by bootstrap methods to create and configure worlds for thin clients. It takes a reference world as input and returns the newly created world, or null if creation fails. The delegate is part of the Unity Netcode library. ```csharp public delegate World AutomaticThinClientWorldsUtility.ThinClientWorldInitializationDelegate(World referenceWorld) ``` -------------------------------- ### Disable Predicted Physics Initialization Source: https://docs.unity3d.com/Packages/com.unity.netcode@1.9/Packages/com.unity.netcode%401.9/manual/physics This code snippet demonstrates how to disable the `PredictedPhysicsConfigSystem` within the `InitializationSystemGroup`. This is useful when the physics simulation is not required inside the `PredictedSimulationSystemGroup`, ensuring the `PhysicsSystemGroup` continues to update normally. ```csharp using Unity.Entities; using Unity.Physics.Systems; [UpdateInGroup(typeof(InitializationSystemGroup))] [CreateAfter(typeof(PredictedPhysicsConfigSystem))] public partial struct DisablePhysicsInitializationIfNotConnect : ISystem { public void OnCreate(ref SystemState state) { state.World.GetExistingSystemManaged().Enabled = false; } } ```