com.unity.netcode.gameobjects@1.8.0

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).

## [1.8.0] - 2023-12-12

### Added

- Added a new RPC attribute, which is simply `Rpc`. (#2762)
  - This is a generic attribute that can perform the functions of both Server and Client RPCs, as well as enabling client-to-client RPCs. Includes several default targets: `Server`, `NotServer`, `Owner`, `NotOwner`, `Me`, `NotMe`, `ClientsAndHost`, and `Everyone`. Runtime overrides are available for any of these targets, as well as for sending to a specific ID or groups of IDs.
  - This attribute also includes the ability to defer RPCs that are sent to the local process to the start of the next frame instead of executing them immediately, treating them as if they had gone across the network. The default behavior is to execute immediately.
  - This attribute effectively replaces `ServerRpc` and `ClientRpc`. `ServerRpc` and `ClientRpc` remain in their existing forms for backward compatibility, but `Rpc` will be the recommended and most supported option.
- Added `NetworkManager.OnConnectionEvent` as a unified connection event callback to notify clients and servers of all client connections and disconnections within the session (#2762)
- Added `NetworkManager.ServerIsHost` and `NetworkBehaviour.ServerIsHost` to allow a client to tell if it is connected to a host or to a dedicated server (#2762)
- Added `SceneEventProgress.SceneManagementNotEnabled` return status to be returned when a `NetworkSceneManager` method is invoked and scene management is not enabled. (#2735)
- Added `SceneEventProgress.ServerOnlyAction` return status to be returned when a `NetworkSceneManager` method is invoked by a client. (#2735)
- Added `NetworkObject.InstantiateAndSpawn` and `NetworkSpawnManager.InstantiateAndSpawn` methods to simplify prefab spawning by assuring that the prefab is valid and applies any override prior to instantiating the `GameObject` and spawning the `NetworkObject` instance. (#2710)

### Fixed

- Fixed issue where a client disconnected by a server-host would not receive a local notification. (#2789)
- Fixed issue where a server-host could shutdown during a relay connection but periodically the transport disconnect message sent to any connected clients could be dropped. (#2789)
- Fixed issue where a host could disconnect its local client but remain running as a server. (#2789)
- Fixed issue where `OnClientDisconnectedCallback` was not being invoked under certain conditions. (#2789)
- Fixed issue where `OnClientDisconnectedCallback` was always returning 0 as the client identifier. (#2789)
- Fixed issue where if a host or server shutdown while a client owned NetworkObjects (other than the player) it would throw an exception. (#2789)
- Fixed issue where setting values on a `NetworkVariable` or `NetworkList` within `OnNetworkDespawn` during a shutdown sequence would throw an exception. (#2789)
- Fixed issue where a teleport state could potentially be overridden by a previous unreliable delta state. (#2777)
- Fixed issue where `NetworkTransform` was using the `NetworkManager.ServerTime.Tick` as opposed to `NetworkManager.NetworkTickSystem.ServerTime.Tick` during the authoritative side's tick update where it performed a delta state check. (#2777)
- Fixed issue where a parented in-scene placed NetworkObject would be destroyed upon a client or server exiting a network session but not unloading the original scene in which the NetworkObject was placed. (#2737)
- Fixed issue where during client synchronization and scene loading, when client synchronization or the scene loading mode are set to `LoadSceneMode.Single`, a `CreateObjectMessage` could be received, processed, and the resultant spawned `NetworkObject` could be instantiated in the client's currently active scene that could, towards the end of the client synchronization or loading process, be unloaded and cause the newly created `NetworkObject` to be destroyed (and throw and exception). (#2735)
- Fixed issue where a `NetworkTransform` instance with interpolation enabled would result in wide visual motion gaps (stuttering) under above normal latency conditions and a 1-5% or higher packet are drop rate. (#2713)
- Fixed issue where  you could not have multiple source network prefab overrides targeting the same network prefab as their override. (#2710)

### Changed
- Changed the server or host shutdown so it will now perform a "soft shutdown" when `NetworkManager.Shutdown` is invoked. This will send a disconnect notification to all connected clients and the server-host will wait for all connected clients to disconnect or timeout after a 5 second period before completing the shutdown process. (#2789)
- Changed `OnClientDisconnectedCallback` will now return the assigned client identifier on the local client side if the client was approved and assigned one prior to being disconnected. (#2789)
- Changed `NetworkTransform.SetState` (and related methods) now are cumulative during a fractional tick period and sent on the next pending tick. (#2777)
- `NetworkManager.ConnectedClientsIds` is now accessible on the client side and will contain the list of all clients in the session, including the host client if the server is operating in host mode (#2762)
- Changed `NetworkSceneManager` to return a `SceneEventProgress` status and not throw exceptions for methods invoked when scene management is disabled and when a client attempts to access a `NetworkSceneManager` method by a client. (#2735)
- Changed `NetworkTransform` authoritative instance tick registration so a single `NetworkTransform` specific tick event update will update all authoritative instances to improve perofmance. (#2713)
- Changed `NetworkPrefabs.OverrideToNetworkPrefab` dictionary is no longer used/populated due to it ending up being related to a regression bug and not allowing more than one override to be assigned to a network prefab asset. (#2710)
- Changed in-scene placed `NetworkObject`s now store their source network prefab asset's `GlobalObjectIdHash` internally that is used, when scene management is disabled, by clients to spawn the correct prefab even if the `NetworkPrefab` entry has an override. This does not impact dynamically spawning the same prefab which will yield the override on both host and client. (#2710)
- Changed in-scene placed `NetworkObject`s no longer require a `NetworkPrefab` entry with `GlobalObjectIdHash` override in order for clients to properly synchronize. (#2710)
- Changed in-scene placed `NetworkObject`s now set their `IsSceneObject` value when generating their `GlobalObjectIdHash` value. (#2710)
- Changed the default `NetworkConfig.SpawnTimeout` value from 1.0s to 10.0s. (#2710)
This commit is contained in:
Unity Technologies
2023-12-12 00:00:00 +00:00
parent 514166e159
commit 07f206ff9e
99 changed files with 8667 additions and 1710 deletions

View File

@@ -26,8 +26,10 @@ namespace Unity.Netcode.Editor.CodeGen
public static readonly string INetworkMessage_FullName = typeof(INetworkMessage).FullName;
public static readonly string ServerRpcAttribute_FullName = typeof(ServerRpcAttribute).FullName;
public static readonly string ClientRpcAttribute_FullName = typeof(ClientRpcAttribute).FullName;
public static readonly string RpcAttribute_FullName = typeof(RpcAttribute).FullName;
public static readonly string ServerRpcParams_FullName = typeof(ServerRpcParams).FullName;
public static readonly string ClientRpcParams_FullName = typeof(ClientRpcParams).FullName;
public static readonly string RpcParams_FullName = typeof(RpcParams).FullName;
public static readonly string ClientRpcSendParams_FullName = typeof(ClientRpcSendParams).FullName;
public static readonly string ClientRpcReceiveParams_FullName = typeof(ClientRpcReceiveParams).FullName;
public static readonly string ServerRpcSendParams_FullName = typeof(ServerRpcSendParams).FullName;

View File

@@ -363,11 +363,14 @@ namespace Unity.Netcode.Editor.CodeGen
private FieldReference m_NetworkManager_LogLevel_FieldRef;
private MethodReference m_NetworkBehaviour___registerRpc_MethodRef;
private TypeReference m_NetworkBehaviour_TypeRef;
private TypeReference m_AttributeParamsType_TypeRef;
private TypeReference m_NetworkVariableBase_TypeRef;
private MethodReference m_NetworkVariableBase_Initialize_MethodRef;
private MethodReference m_NetworkBehaviour___nameNetworkVariable_MethodRef;
private MethodReference m_NetworkBehaviour_beginSendServerRpc_MethodRef;
private MethodReference m_NetworkBehaviour_endSendServerRpc_MethodRef;
private MethodReference m_NetworkBehaviour_beginSendRpc_MethodRef;
private MethodReference m_NetworkBehaviour_endSendRpc_MethodRef;
private MethodReference m_NetworkBehaviour_beginSendClientRpc_MethodRef;
private MethodReference m_NetworkBehaviour_endSendClientRpc_MethodRef;
private FieldReference m_NetworkBehaviour_rpc_exec_stage_FieldRef;
@@ -378,9 +381,13 @@ namespace Unity.Netcode.Editor.CodeGen
private TypeReference m_RpcParams_TypeRef;
private FieldReference m_RpcParams_Server_FieldRef;
private FieldReference m_RpcParams_Client_FieldRef;
private FieldReference m_RpcParams_Ext_FieldRef;
private TypeReference m_ServerRpcParams_TypeRef;
private FieldReference m_ServerRpcParams_Receive_FieldRef;
private FieldReference m_ServerRpcParams_Receive_SenderClientId_FieldRef;
private FieldReference m_UniversalRpcParams_Receive_FieldRef;
private FieldReference m_UniversalRpcParams_Receive_SenderClientId_FieldRef;
private TypeReference m_UniversalRpcParams_TypeRef;
private TypeReference m_ClientRpcParams_TypeRef;
private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef;
private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyArray_MethodRef;
@@ -495,6 +502,8 @@ namespace Unity.Netcode.Editor.CodeGen
private const string k_NetworkBehaviour_NetworkVariableFields = nameof(NetworkBehaviour.NetworkVariableFields);
private const string k_NetworkBehaviour_beginSendServerRpc = nameof(NetworkBehaviour.__beginSendServerRpc);
private const string k_NetworkBehaviour_endSendServerRpc = nameof(NetworkBehaviour.__endSendServerRpc);
private const string k_NetworkBehaviour_beginSendRpc = nameof(NetworkBehaviour.__beginSendRpc);
private const string k_NetworkBehaviour_endSendRpc = nameof(NetworkBehaviour.__endSendRpc);
private const string k_NetworkBehaviour_beginSendClientRpc = nameof(NetworkBehaviour.__beginSendClientRpc);
private const string k_NetworkBehaviour_endSendClientRpc = nameof(NetworkBehaviour.__endSendClientRpc);
private const string k_NetworkBehaviour___initializeVariables = nameof(NetworkBehaviour.__initializeVariables);
@@ -511,8 +520,11 @@ namespace Unity.Netcode.Editor.CodeGen
private const string k_ServerRpcAttribute_RequireOwnership = nameof(ServerRpcAttribute.RequireOwnership);
private const string k_RpcParams_Server = nameof(__RpcParams.Server);
private const string k_RpcParams_Client = nameof(__RpcParams.Client);
private const string k_RpcParams_Ext = nameof(__RpcParams.Ext);
private const string k_ServerRpcParams_Receive = nameof(ServerRpcParams.Receive);
private const string k_RpcParams_Receive = nameof(RpcParams.Receive);
private const string k_ServerRpcReceiveParams_SenderClientId = nameof(ServerRpcReceiveParams.SenderClientId);
private const string k_RpcReceiveParams_SenderClientId = nameof(RpcReceiveParams.SenderClientId);
// CodeGen cannot reference the collections assembly to do a typeof() on it due to a bug that causes that to crash.
private const string k_INativeListBool_FullName = "Unity.Collections.INativeList`1<System.Byte>";
@@ -545,13 +557,20 @@ namespace Unity.Netcode.Editor.CodeGen
TypeDefinition rpcParamsTypeDef = null;
TypeDefinition serverRpcParamsTypeDef = null;
TypeDefinition clientRpcParamsTypeDef = null;
TypeDefinition universalRpcParamsTypeDef = null;
TypeDefinition fastBufferWriterTypeDef = null;
TypeDefinition fastBufferReaderTypeDef = null;
TypeDefinition networkVariableSerializationTypesTypeDef = null;
TypeDefinition bytePackerTypeDef = null;
TypeDefinition byteUnpackerTypeDef = null;
TypeDefinition attributeParamsType = null;
foreach (var netcodeTypeDef in m_NetcodeModule.GetAllTypes())
{
if (attributeParamsType == null && netcodeTypeDef.Name == nameof(RpcAttribute.RpcAttributeParams))
{
attributeParamsType = netcodeTypeDef;
continue;
}
if (networkManagerTypeDef == null && netcodeTypeDef.Name == nameof(NetworkManager))
{
networkManagerTypeDef = netcodeTypeDef;
@@ -588,6 +607,12 @@ namespace Unity.Netcode.Editor.CodeGen
continue;
}
if (universalRpcParamsTypeDef == null && netcodeTypeDef.Name == nameof(RpcParams))
{
universalRpcParamsTypeDef = netcodeTypeDef;
continue;
}
if (clientRpcParamsTypeDef == null && netcodeTypeDef.Name == nameof(ClientRpcParams))
{
clientRpcParamsTypeDef = netcodeTypeDef;
@@ -662,6 +687,8 @@ namespace Unity.Netcode.Editor.CodeGen
}
}
m_AttributeParamsType_TypeRef = moduleDefinition.ImportReference(attributeParamsType);
foreach (var fieldDef in networkManagerTypeDef.Fields)
{
switch (fieldDef.Name)
@@ -696,6 +723,12 @@ namespace Unity.Netcode.Editor.CodeGen
case k_NetworkBehaviour_endSendServerRpc:
m_NetworkBehaviour_endSendServerRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
break;
case k_NetworkBehaviour_beginSendRpc:
m_NetworkBehaviour_beginSendRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
break;
case k_NetworkBehaviour_endSendRpc:
m_NetworkBehaviour_endSendRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
break;
case k_NetworkBehaviour_beginSendClientRpc:
m_NetworkBehaviour_beginSendClientRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
break;
@@ -763,6 +796,9 @@ namespace Unity.Netcode.Editor.CodeGen
case k_RpcParams_Client:
m_RpcParams_Client_FieldRef = moduleDefinition.ImportReference(fieldDef);
break;
case k_RpcParams_Ext:
m_RpcParams_Ext_FieldRef = moduleDefinition.ImportReference(fieldDef);
break;
}
}
@@ -786,6 +822,26 @@ namespace Unity.Netcode.Editor.CodeGen
break;
}
}
m_UniversalRpcParams_TypeRef = moduleDefinition.ImportReference(rpcParamsTypeDef);
foreach (var fieldDef in rpcParamsTypeDef.Fields)
{
switch (fieldDef.Name)
{
case k_RpcParams_Receive:
foreach (var recvFieldDef in fieldDef.FieldType.Resolve().Fields)
{
switch (recvFieldDef.Name)
{
case k_RpcReceiveParams_SenderClientId:
m_UniversalRpcParams_Receive_SenderClientId_FieldRef = moduleDefinition.ImportReference(recvFieldDef);
break;
}
}
m_UniversalRpcParams_Receive_FieldRef = moduleDefinition.ImportReference(fieldDef);
break;
}
}
m_ClientRpcParams_TypeRef = moduleDefinition.ImportReference(clientRpcParamsTypeDef);
m_FastBufferWriter_TypeRef = moduleDefinition.ImportReference(fastBufferWriterTypeDef);
@@ -1354,7 +1410,8 @@ namespace Unity.Netcode.Editor.CodeGen
var customAttributeType_FullName = customAttribute.AttributeType.FullName;
if (customAttributeType_FullName == CodeGenHelpers.ServerRpcAttribute_FullName ||
customAttributeType_FullName == CodeGenHelpers.ClientRpcAttribute_FullName)
customAttributeType_FullName == CodeGenHelpers.ClientRpcAttribute_FullName ||
customAttributeType_FullName == CodeGenHelpers.RpcAttribute_FullName)
{
bool isValid = true;
@@ -1389,6 +1446,13 @@ namespace Unity.Netcode.Editor.CodeGen
isValid = false;
}
if (customAttributeType_FullName == CodeGenHelpers.RpcAttribute_FullName &&
!methodDefinition.Name.EndsWith("Rpc", StringComparison.OrdinalIgnoreCase))
{
m_Diagnostics.AddError(methodDefinition, "Rpc method must end with 'Rpc' suffix!");
isValid = false;
}
if (customAttributeType_FullName == CodeGenHelpers.ClientRpcAttribute_FullName &&
!methodDefinition.Name.EndsWith("ClientRpc", StringComparison.OrdinalIgnoreCase))
{
@@ -1411,11 +1475,15 @@ namespace Unity.Netcode.Editor.CodeGen
{
if (methodDefinition.Name.EndsWith("ServerRpc", StringComparison.OrdinalIgnoreCase))
{
m_Diagnostics.AddError(methodDefinition, "ServerRpc method must be marked with 'ServerRpc' attribute!");
m_Diagnostics.AddError(methodDefinition, $"ServerRpc method {methodDefinition} must be marked with 'ServerRpc' attribute!");
}
else if (methodDefinition.Name.EndsWith("ClientRpc", StringComparison.OrdinalIgnoreCase))
{
m_Diagnostics.AddError(methodDefinition, "ClientRpc method must be marked with 'ClientRpc' attribute!");
m_Diagnostics.AddError(methodDefinition, $"ClientRpc method {methodDefinition} must be marked with 'ClientRpc' attribute!");
}
else if (methodDefinition.Name.EndsWith("ExtRpc", StringComparison.OrdinalIgnoreCase))
{
m_Diagnostics.AddError(methodDefinition, $"Ext Rpc method {methodDefinition} must be marked with 'ExtRpc' attribute!");
}
return null;
@@ -1887,8 +1955,17 @@ namespace Unity.Netcode.Editor.CodeGen
var instructions = new List<Instruction>();
var processor = methodDefinition.Body.GetILProcessor();
var isServerRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.ServerRpcAttribute_FullName;
var isClientRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.ClientRpcAttribute_FullName;
var isGenericRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.RpcAttribute_FullName;
var requireOwnership = true; // default value MUST be == `ServerRpcAttribute.RequireOwnership`
var rpcDelivery = RpcDelivery.Reliable; // default value MUST be == `RpcAttribute.Delivery`
var defaultTarget = SendTo.Everyone;
var allowTargetOverride = false;
if (isGenericRpc)
{
defaultTarget = (SendTo)rpcAttribute.ConstructorArguments[0].Value;
}
foreach (var attrField in rpcAttribute.Fields)
{
switch (attrField.Name)
@@ -1899,6 +1976,9 @@ namespace Unity.Netcode.Editor.CodeGen
case k_ServerRpcAttribute_RequireOwnership:
requireOwnership = attrField.Argument.Type == typeSystem.Boolean && (bool)attrField.Argument.Value;
break;
case nameof(RpcAttribute.AllowTargetOverride):
allowTargetOverride = attrField.Argument.Type == typeSystem.Boolean && (bool)attrField.Argument.Value;
break;
}
}
@@ -1906,7 +1986,33 @@ namespace Unity.Netcode.Editor.CodeGen
var hasRpcParams =
paramCount > 0 &&
((isServerRpc && methodDefinition.Parameters[paramCount - 1].ParameterType.FullName == CodeGenHelpers.ServerRpcParams_FullName) ||
(!isServerRpc && methodDefinition.Parameters[paramCount - 1].ParameterType.FullName == CodeGenHelpers.ClientRpcParams_FullName));
(isClientRpc && methodDefinition.Parameters[paramCount - 1].ParameterType.FullName == CodeGenHelpers.ClientRpcParams_FullName) ||
(isGenericRpc && methodDefinition.Parameters[paramCount - 1].ParameterType.FullName == CodeGenHelpers.RpcParams_FullName));
if (isGenericRpc && defaultTarget == SendTo.SpecifiedInParams)
{
if (!hasRpcParams)
{
m_Diagnostics.AddError($"{methodDefinition}: {nameof(SendTo)}.{nameof(SendTo.SpecifiedInParams)} cannot be used without a final parameter of type {CodeGenHelpers.RpcParams_FullName}.");
}
foreach (var attrField in rpcAttribute.Fields)
{
switch (attrField.Name)
{
case nameof(RpcAttribute.AllowTargetOverride):
m_Diagnostics.AddWarning($"{methodDefinition}: {nameof(RpcAttribute.AllowTargetOverride)} is ignored with {nameof(SendTo)}.{nameof(SendTo.SpecifiedInParams)}");
break;
}
}
}
if (isGenericRpc && allowTargetOverride)
{
if (!hasRpcParams)
{
m_Diagnostics.AddError($"{methodDefinition}: {nameof(RpcAttribute.AllowTargetOverride)} cannot be used without a final parameter of type {CodeGenHelpers.RpcParams_FullName}.");
}
}
methodDefinition.Body.InitLocals = true;
// NetworkManager networkManager;
@@ -1919,10 +2025,17 @@ namespace Unity.Netcode.Editor.CodeGen
// XXXRpcParams
if (!hasRpcParams)
{
methodDefinition.Body.Variables.Add(new VariableDefinition(isServerRpc ? m_ServerRpcParams_TypeRef : m_ClientRpcParams_TypeRef));
methodDefinition.Body.Variables.Add(new VariableDefinition(isServerRpc ? m_ServerRpcParams_TypeRef : (isClientRpc ? m_ClientRpcParams_TypeRef : m_UniversalRpcParams_TypeRef)));
}
int rpcParamsIdx = !hasRpcParams ? methodDefinition.Body.Variables.Count - 1 : -1;
if (isGenericRpc)
{
methodDefinition.Body.Variables.Add(new VariableDefinition(m_AttributeParamsType_TypeRef));
}
int rpcAttributeParamsIdx = isGenericRpc ? methodDefinition.Body.Variables.Count - 1 : -1;
{
var returnInstr = processor.Create(OpCodes.Ret);
var lastInstr = processor.Create(OpCodes.Nop);
@@ -1952,20 +2065,23 @@ namespace Unity.Netcode.Editor.CodeGen
// if (__rpc_exec_stage != __RpcExecStage.Client) -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)(isServerRpc ? NetworkBehaviour.__RpcExecStage.Server : NetworkBehaviour.__RpcExecStage.Client)));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Execute));
instructions.Add(processor.Create(OpCodes.Ceq));
instructions.Add(processor.Create(OpCodes.Ldc_I4, 0));
instructions.Add(processor.Create(OpCodes.Ceq));
instructions.Add(processor.Create(OpCodes.Brfalse, lastInstr));
// if (networkManager.IsClient || networkManager.IsHost) { ... } -> ServerRpc
// if (networkManager.IsServer || networkManager.IsHost) { ... } -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, isServerRpc ? m_NetworkManager_getIsClient_MethodRef : m_NetworkManager_getIsServer_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, beginInstr));
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, m_NetworkManager_getIsHost_MethodRef));
instructions.Add(processor.Create(OpCodes.Brfalse, lastInstr));
if (!isGenericRpc)
{
// if (networkManager.IsClient || networkManager.IsHost) { ... } -> ServerRpc
// if (networkManager.IsServer || networkManager.IsHost) { ... } -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, isServerRpc ? m_NetworkManager_getIsClient_MethodRef : m_NetworkManager_getIsServer_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, beginInstr));
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, m_NetworkManager_getIsHost_MethodRef));
instructions.Add(processor.Create(OpCodes.Brfalse, lastInstr));
}
instructions.Add(beginInstr);
@@ -2027,7 +2143,7 @@ namespace Unity.Netcode.Editor.CodeGen
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_beginSendServerRpc_MethodRef));
instructions.Add(processor.Create(OpCodes.Stloc, bufWriterLocIdx));
}
else
else if (isClientRpc)
{
// ClientRpc
@@ -2047,6 +2163,89 @@ namespace Unity.Netcode.Editor.CodeGen
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_beginSendClientRpc_MethodRef));
instructions.Add(processor.Create(OpCodes.Stloc, bufWriterLocIdx));
}
else
{
// Generic RPC
// var bufferWriter = __beginSendRpc(rpcMethodId, rpcParams, rpcAttributeParams, defaultTarget, rpcDelivery);
instructions.Add(processor.Create(OpCodes.Ldarg_0));
// rpcMethodId
instructions.Add(processor.Create(OpCodes.Ldc_I4, unchecked((int)rpcMethodId)));
// rpcParams
instructions.Add(hasRpcParams ? processor.Create(OpCodes.Ldarg, paramCount) : processor.Create(OpCodes.Ldloc, rpcParamsIdx));
// rpcAttributeParams
instructions.Add(processor.Create(OpCodes.Ldloca, rpcAttributeParamsIdx));
instructions.Add(processor.Create(OpCodes.Initobj, m_AttributeParamsType_TypeRef));
RpcAttribute.RpcAttributeParams dflt = default;
foreach (var field in rpcAttribute.Fields)
{
var found = false;
foreach (var attrField in m_AttributeParamsType_TypeRef.Resolve().Fields)
{
if (attrField.Name == field.Name)
{
found = true;
var value = field.Argument.Value;
var paramField = dflt.GetType().GetField(attrField.Name);
if (value != paramField.GetValue(dflt))
{
instructions.Add(processor.Create(OpCodes.Ldloca, rpcAttributeParamsIdx));
var type = value.GetType();
if (type == typeof(bool))
{
instructions.Add(processor.Create(OpCodes.Ldc_I4, (bool)value ? 1 : 0));
}
else if (type == typeof(short) || type == typeof(int) || type == typeof(ushort)
|| type == typeof(byte) || type == typeof(sbyte) || type == typeof(char))
{
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)value));
}
else if (type == typeof(long) || type == typeof(ulong))
{
instructions.Add(processor.Create(OpCodes.Ldc_I8, (long)value));
}
else if (type == typeof(float))
{
instructions.Add(processor.Create(OpCodes.Ldc_R8, (float)value));
}
else if (type == typeof(double))
{
instructions.Add(processor.Create(OpCodes.Ldc_R8, (double)value));
}
else
{
m_Diagnostics.AddError("Unsupported attribute parameter type.");
}
}
instructions.Add(processor.Create(OpCodes.Stfld, m_MainModule.ImportReference(attrField)));
break;
}
}
if (!found)
{
m_Diagnostics.AddError($"{nameof(RpcAttribute)} contains field {field} which is not present in {nameof(RpcAttribute.RpcAttributeParams)}.");
}
}
instructions.Add(processor.Create(OpCodes.Ldloc, rpcAttributeParamsIdx));
// defaultTarget
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)defaultTarget));
// rpcDelivery
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)rpcDelivery));
// __beginSendRpc
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_beginSendRpc_MethodRef));
instructions.Add(processor.Create(OpCodes.Stloc, bufWriterLocIdx));
}
// write method parameters into stream
for (int paramIndex = 0; paramIndex < paramCount; ++paramIndex)
@@ -2075,7 +2274,7 @@ namespace Unity.Netcode.Editor.CodeGen
}
if (!isServerRpc)
{
m_Diagnostics.AddError($"ClientRpcs may not accept {nameof(ServerRpcParams)} as a parameter.");
m_Diagnostics.AddError($"Only ServerRpcs may accept {nameof(ServerRpcParams)} as a parameter.");
}
continue;
}
@@ -2086,9 +2285,22 @@ namespace Unity.Netcode.Editor.CodeGen
{
m_Diagnostics.AddError(methodDefinition, $"{nameof(ClientRpcParams)} must be the last parameter in a ClientRpc.");
}
if (isServerRpc)
if (!isClientRpc)
{
m_Diagnostics.AddError($"ServerRpcs may not accept {nameof(ClientRpcParams)} as a parameter.");
m_Diagnostics.AddError($"Only clientRpcs may accept {nameof(ClientRpcParams)} as a parameter.");
}
continue;
}
// RpcParams
if (paramType.FullName == CodeGenHelpers.RpcParams_FullName)
{
if (paramIndex != paramCount - 1)
{
m_Diagnostics.AddError(methodDefinition, $"{nameof(RpcParams)} must be the last parameter in a ClientRpc.");
}
if (!isGenericRpc)
{
m_Diagnostics.AddError($"Only Rpcs may accept {nameof(RpcParams)} as a parameter.");
}
continue;
}
@@ -2251,7 +2463,7 @@ namespace Unity.Netcode.Editor.CodeGen
// __endSendServerRpc
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_endSendServerRpc_MethodRef));
}
else
else if (isClientRpc)
{
// ClientRpc
@@ -2279,6 +2491,41 @@ namespace Unity.Netcode.Editor.CodeGen
// __endSendClientRpc
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_endSendClientRpc_MethodRef));
}
else
{
// Generic Rpc
// __endSendRpc(ref bufferWriter, rpcMethodId, rpcParams, rpcAttributeParams, defaultTarget, rpcDelivery);
instructions.Add(processor.Create(OpCodes.Ldarg_0));
// bufferWriter
instructions.Add(processor.Create(OpCodes.Ldloca, bufWriterLocIdx));
// rpcMethodId
instructions.Add(processor.Create(OpCodes.Ldc_I4, unchecked((int)rpcMethodId)));
if (hasRpcParams)
{
// rpcParams
instructions.Add(processor.Create(OpCodes.Ldarg, paramCount));
}
else
{
// default
instructions.Add(processor.Create(OpCodes.Ldloc, rpcParamsIdx));
}
// rpcAttributeParams
instructions.Add(processor.Create(OpCodes.Ldloc, rpcAttributeParamsIdx));
// defaultTarget
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)defaultTarget));
// rpcDelivery
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)rpcDelivery));
// __endSendClientRpc
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_endSendRpc_MethodRef));
}
instructions.Add(lastInstr);
}
@@ -2287,25 +2534,53 @@ namespace Unity.Netcode.Editor.CodeGen
var returnInstr = processor.Create(OpCodes.Ret);
var lastInstr = processor.Create(OpCodes.Nop);
// if (__rpc_exec_stage == __RpcExecStage.Server) -> ServerRpc
// if (__rpc_exec_stage == __RpcExecStage.Client) -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)(isServerRpc ? NetworkBehaviour.__RpcExecStage.Server : NetworkBehaviour.__RpcExecStage.Client)));
instructions.Add(processor.Create(OpCodes.Ceq));
instructions.Add(processor.Create(OpCodes.Brfalse, returnInstr));
if (!isGenericRpc)
{
// if (__rpc_exec_stage == __RpcExecStage.Execute)
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Execute));
instructions.Add(processor.Create(OpCodes.Ceq));
instructions.Add(processor.Create(OpCodes.Brfalse, returnInstr));
// if (networkManager.IsServer || networkManager.IsHost) -> ServerRpc
// if (networkManager.IsClient || networkManager.IsHost) -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, isServerRpc ? m_NetworkManager_getIsServer_MethodRef : m_NetworkManager_getIsClient_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, lastInstr));
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, m_NetworkManager_getIsHost_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, lastInstr));
// if (networkManager.IsServer || networkManager.IsHost) -> ServerRpc
// if (networkManager.IsClient || networkManager.IsHost) -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, isServerRpc ? m_NetworkManager_getIsServer_MethodRef : m_NetworkManager_getIsClient_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, lastInstr));
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, m_NetworkManager_getIsHost_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, lastInstr));
instructions.Add(returnInstr);
instructions.Add(lastInstr);
// This needs to be set back before executing the callback or else sending another RPC
// from within an RPC will not work.
// __rpc_exec_stage = __RpcExecStage.Send
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Send));
instructions.Add(processor.Create(OpCodes.Stfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
}
else
{
// if (__rpc_exec_stage == __RpcExecStage.Execute)
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Execute));
instructions.Add(processor.Create(OpCodes.Ceq));
instructions.Add(processor.Create(OpCodes.Brtrue, lastInstr));
instructions.Add(returnInstr);
instructions.Add(lastInstr);
// This needs to be set back before executing the callback or else sending another RPC
// from within an RPC will not work.
// __rpc_exec_stage = __RpcExecStage.Send
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Send));
instructions.Add(processor.Create(OpCodes.Stfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
}
instructions.Add(returnInstr);
instructions.Add(lastInstr);
}
instructions.Reverse();
@@ -2458,6 +2733,8 @@ namespace Unity.Netcode.Editor.CodeGen
var processor = rpcHandler.Body.GetILProcessor();
var isServerRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.ServerRpcAttribute_FullName;
var isCientRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.ClientRpcAttribute_FullName;
var isGenericRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.RpcAttribute_FullName;
var requireOwnership = true; // default value MUST be == `ServerRpcAttribute.RequireOwnership`
foreach (var attrField in rpcAttribute.Fields)
{
@@ -2564,6 +2841,15 @@ namespace Unity.Netcode.Editor.CodeGen
processor.Emit(OpCodes.Stloc, localIndex);
continue;
}
// RpcParams
if (paramType.FullName == CodeGenHelpers.RpcParams_FullName)
{
processor.Emit(OpCodes.Ldarg_2);
processor.Emit(OpCodes.Ldfld, m_RpcParams_Ext_FieldRef);
processor.Emit(OpCodes.Stloc, localIndex);
continue;
}
}
Instruction jumpInstruction = null;
@@ -2690,7 +2976,7 @@ namespace Unity.Netcode.Editor.CodeGen
// NetworkBehaviour.__rpc_exec_stage = __RpcExecStage.Server; -> ServerRpc
// NetworkBehaviour.__rpc_exec_stage = __RpcExecStage.Client; -> ClientRpc
processor.Emit(OpCodes.Ldarg_0);
processor.Emit(OpCodes.Ldc_I4, (int)(isServerRpc ? NetworkBehaviour.__RpcExecStage.Server : NetworkBehaviour.__RpcExecStage.Client));
processor.Emit(OpCodes.Ldc_I4, (int)(NetworkBehaviour.__RpcExecStage.Execute));
processor.Emit(OpCodes.Stfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef);
// NetworkBehaviour.XXXRpc(...);
@@ -2713,7 +2999,7 @@ namespace Unity.Netcode.Editor.CodeGen
// NetworkBehaviour.__rpc_exec_stage = __RpcExecStage.None;
processor.Emit(OpCodes.Ldarg_0);
processor.Emit(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.None);
processor.Emit(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Send);
processor.Emit(OpCodes.Stfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef);
processor.Emit(OpCodes.Ret);

View File

@@ -2,6 +2,7 @@ using System.Collections.Generic;
using System.IO;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using Unity.CompilationPipeline.Common.Diagnostics;
using Unity.CompilationPipeline.Common.ILPostProcessing;
using ILPPInterface = Unity.CompilationPipeline.Common.ILPostProcessing.ILPostProcessor;
@@ -52,6 +53,15 @@ namespace Unity.Netcode.Editor.CodeGen
case nameof(NetworkBehaviour):
ProcessNetworkBehaviour(typeDefinition);
break;
case nameof(RpcAttribute):
foreach (var methodDefinition in typeDefinition.GetConstructors())
{
if (methodDefinition.Parameters.Count == 0)
{
methodDefinition.IsPublic = true;
}
}
break;
case nameof(__RpcParams):
case nameof(RpcFallbackSerialization):
typeDefinition.IsPublic = true;
@@ -154,6 +164,8 @@ namespace Unity.Netcode.Editor.CodeGen
methodDefinition.Name == nameof(NetworkBehaviour.__endSendServerRpc) ||
methodDefinition.Name == nameof(NetworkBehaviour.__beginSendClientRpc) ||
methodDefinition.Name == nameof(NetworkBehaviour.__endSendClientRpc) ||
methodDefinition.Name == nameof(NetworkBehaviour.__beginSendRpc) ||
methodDefinition.Name == nameof(NetworkBehaviour.__endSendRpc) ||
methodDefinition.Name == nameof(NetworkBehaviour.__initializeVariables) ||
methodDefinition.Name == nameof(NetworkBehaviour.__initializeRpcs) ||
methodDefinition.Name == nameof(NetworkBehaviour.__registerRpc) ||

View File

@@ -1,3 +1,6 @@
#if UNITY_2022_3_OR_NEWER && (RELAY_SDK_INSTALLED && !UNITY_WEBGL ) || (RELAY_SDK_INSTALLED && UNITY_WEBGL && UTP_TRANSPORT_2_0_ABOVE)
#define RELAY_INTEGRATION_AVAILABLE
#endif
using System;
using System.Collections.Generic;
using System.IO;
@@ -48,6 +51,27 @@ namespace Unity.Netcode.Editor
private readonly List<Type> m_TransportTypes = new List<Type>();
private string[] m_TransportNames = { "Select transport..." };
/// <inheritdoc/>
public override void OnInspectorGUI()
{
Initialize();
CheckNullProperties();
#if !MULTIPLAYER_TOOLS
DrawInstallMultiplayerToolsTip();
#endif
if (m_NetworkManager.IsServer || m_NetworkManager.IsClient)
{
DrawDisconnectButton();
}
else
{
DrawAllPropertyFields();
ShowStartConnectionButtons();
}
}
private void ReloadTransports()
{
m_TransportTypes.Clear();
@@ -138,209 +162,311 @@ namespace Unity.Netcode.Editor
.FindPropertyRelative(nameof(NetworkPrefabs.NetworkPrefabsLists));
}
/// <inheritdoc/>
public override void OnInspectorGUI()
private void DrawAllPropertyFields()
{
Initialize();
CheckNullProperties();
serializedObject.Update();
EditorGUILayout.PropertyField(m_RunInBackgroundProperty);
EditorGUILayout.PropertyField(m_LogLevelProperty);
EditorGUILayout.Space();
#if !MULTIPLAYER_TOOLS
DrawInstallMultiplayerToolsTip();
#endif
EditorGUILayout.PropertyField(m_PlayerPrefabProperty);
EditorGUILayout.Space();
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
DrawPrefabListField();
EditorGUILayout.Space();
EditorGUILayout.LabelField("General", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_ProtocolVersionProperty);
DrawTransportField();
EditorGUILayout.PropertyField(m_TickRateProperty);
EditorGUILayout.LabelField("Performance", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_EnsureNetworkVariableLengthSafetyProperty);
EditorGUILayout.LabelField("Connection", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_ConnectionApprovalProperty);
using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.ConnectionApproval))
{
serializedObject.Update();
EditorGUILayout.PropertyField(m_RunInBackgroundProperty);
EditorGUILayout.PropertyField(m_LogLevelProperty);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_PlayerPrefabProperty);
EditorGUILayout.Space();
if (m_NetworkManager.NetworkConfig.HasOldPrefabList())
{
EditorGUILayout.HelpBox("Network Prefabs serialized in old format. Migrate to new format to edit the list.", MessageType.Info);
if (GUILayout.Button(new GUIContent("Migrate Prefab List", "Converts the old format Network Prefab list to a new Scriptable Object")))
{
// Default directory
var directory = "Assets/";
var assetPath = AssetDatabase.GetAssetPath(m_NetworkManager);
if (assetPath == "")
{
assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(m_NetworkManager);
}
if (assetPath != "")
{
directory = Path.GetDirectoryName(assetPath);
}
else
{
#if UNITY_2021_1_OR_NEWER
var prefabStage = UnityEditor.SceneManagement.PrefabStageUtility.GetPrefabStage(m_NetworkManager.gameObject);
#else
var prefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetPrefabStage(m_NetworkManager.gameObject);
#endif
if (prefabStage != null)
{
var prefabPath = prefabStage.assetPath;
if (!string.IsNullOrEmpty(prefabPath))
{
directory = Path.GetDirectoryName(prefabPath);
}
}
if (m_NetworkManager.gameObject.scene != null)
{
var scenePath = m_NetworkManager.gameObject.scene.path;
if (!string.IsNullOrEmpty(scenePath))
{
directory = Path.GetDirectoryName(scenePath);
}
}
}
var networkPrefabs = m_NetworkManager.NetworkConfig.MigrateOldNetworkPrefabsToNetworkPrefabsList();
string path = Path.Combine(directory, $"NetworkPrefabs-{m_NetworkManager.GetInstanceID()}.asset");
Debug.Log("Saving migrated Network Prefabs List to " + path);
AssetDatabase.CreateAsset(networkPrefabs, path);
EditorUtility.SetDirty(m_NetworkManager);
}
}
else
{
if (m_NetworkManager.NetworkConfig.Prefabs.NetworkPrefabsLists.Count == 0)
{
EditorGUILayout.HelpBox("You have no prefab list selected. You will have to add your prefabs manually at runtime for netcode to work.", MessageType.Warning);
}
EditorGUILayout.PropertyField(m_PrefabsList);
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("General", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_ProtocolVersionProperty);
EditorGUILayout.PropertyField(m_NetworkTransportProperty);
if (m_NetworkTransportProperty.objectReferenceValue == null)
{
EditorGUILayout.HelpBox("You have no transport selected. A transport is required for netcode to work. Which one do you want?", MessageType.Warning);
int selection = EditorGUILayout.Popup(0, m_TransportNames);
if (selection > 0)
{
ReloadTransports();
var transportComponent = m_NetworkManager.gameObject.GetComponent(m_TransportTypes[selection - 1]) ?? m_NetworkManager.gameObject.AddComponent(m_TransportTypes[selection - 1]);
m_NetworkTransportProperty.objectReferenceValue = transportComponent;
Repaint();
}
}
EditorGUILayout.PropertyField(m_TickRateProperty);
EditorGUILayout.LabelField("Performance", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_EnsureNetworkVariableLengthSafetyProperty);
EditorGUILayout.LabelField("Connection", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_ConnectionApprovalProperty);
using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.ConnectionApproval))
{
EditorGUILayout.PropertyField(m_ClientConnectionBufferTimeoutProperty);
}
EditorGUILayout.LabelField("Spawning", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_ForceSamePrefabsProperty);
EditorGUILayout.PropertyField(m_RecycleNetworkIdsProperty);
using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.RecycleNetworkIds))
{
EditorGUILayout.PropertyField(m_NetworkIdRecycleDelayProperty);
}
EditorGUILayout.LabelField("Bandwidth", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_RpcHashSizeProperty);
EditorGUILayout.LabelField("Scene Management", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_EnableSceneManagementProperty);
using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.EnableSceneManagement))
{
EditorGUILayout.PropertyField(m_LoadSceneTimeOutProperty);
}
serializedObject.ApplyModifiedProperties();
// Start buttons below
{
string buttonDisabledReasonSuffix = "";
if (!EditorApplication.isPlaying)
{
buttonDisabledReasonSuffix = ". This can only be done in play mode";
GUI.enabled = false;
}
if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix)))
{
m_NetworkManager.StartHost();
}
if (GUILayout.Button(new GUIContent("Start Server", "Starts a server instance" + buttonDisabledReasonSuffix)))
{
m_NetworkManager.StartServer();
}
if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix)))
{
m_NetworkManager.StartClient();
}
if (!EditorApplication.isPlaying)
{
GUI.enabled = true;
}
}
EditorGUILayout.PropertyField(m_ClientConnectionBufferTimeoutProperty);
}
else
EditorGUILayout.LabelField("Spawning", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_ForceSamePrefabsProperty);
EditorGUILayout.PropertyField(m_RecycleNetworkIdsProperty);
using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.RecycleNetworkIds))
{
string instanceType = string.Empty;
EditorGUILayout.PropertyField(m_NetworkIdRecycleDelayProperty);
}
if (m_NetworkManager.IsHost)
{
instanceType = "Host";
}
else if (m_NetworkManager.IsServer)
{
instanceType = "Server";
}
else if (m_NetworkManager.IsClient)
{
instanceType = "Client";
}
EditorGUILayout.LabelField("Bandwidth", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_RpcHashSizeProperty);
EditorGUILayout.HelpBox("You cannot edit the NetworkConfig when a " + instanceType + " is running.", MessageType.Info);
EditorGUILayout.LabelField("Scene Management", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_EnableSceneManagementProperty);
if (GUILayout.Button(new GUIContent("Stop " + instanceType, "Stops the " + instanceType + " instance.")))
using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.EnableSceneManagement))
{
EditorGUILayout.PropertyField(m_LoadSceneTimeOutProperty);
}
serializedObject.ApplyModifiedProperties();
}
private void DrawTransportField()
{
#if RELAY_INTEGRATION_AVAILABLE
var useRelay = EditorPrefs.GetBool(k_UseEasyRelayIntegrationKey, false);
#else
var useRelay = false;
#endif
if (useRelay)
{
EditorGUILayout.HelpBox("Test connection with relay is enabled, so the default Unity Transport will be used", MessageType.Info);
GUI.enabled = false;
EditorGUILayout.PropertyField(m_NetworkTransportProperty);
GUI.enabled = true;
return;
}
EditorGUILayout.PropertyField(m_NetworkTransportProperty);
if (m_NetworkTransportProperty.objectReferenceValue == null)
{
EditorGUILayout.HelpBox("You have no transport selected. A transport is required for netcode to work. Which one do you want?", MessageType.Warning);
int selection = EditorGUILayout.Popup(0, m_TransportNames);
if (selection > 0)
{
m_NetworkManager.Shutdown();
ReloadTransports();
var transportComponent = m_NetworkManager.gameObject.GetComponent(m_TransportTypes[selection - 1]) ?? m_NetworkManager.gameObject.AddComponent(m_TransportTypes[selection - 1]);
m_NetworkTransportProperty.objectReferenceValue = transportComponent;
Repaint();
}
}
}
#if RELAY_INTEGRATION_AVAILABLE
private readonly string k_UseEasyRelayIntegrationKey = "NetworkManagerUI_UseRelay_" + Application.dataPath.GetHashCode();
private string m_JoinCode = "";
private string m_StartConnectionError = null;
private string m_Region = "";
// wait for next frame so that ImGui finishes the current frame
private static void RunNextFrame(Action action) => EditorApplication.delayCall += () => action();
#endif
private void ShowStartConnectionButtons()
{
EditorGUILayout.LabelField("Start Connection", EditorStyles.boldLabel);
#if RELAY_INTEGRATION_AVAILABLE
// use editor prefs to persist the setting when entering / leaving play mode / exiting Unity
var useRelay = EditorPrefs.GetBool(k_UseEasyRelayIntegrationKey, false);
GUILayout.BeginHorizontal();
useRelay = GUILayout.Toggle(useRelay, "Try Relay in the Editor");
var icon = EditorGUIUtility.IconContent("_Help");
icon.tooltip = "This will help you test relay in the Editor. Click here to know how to integrate Relay in your build";
if (GUILayout.Button(icon, GUIStyle.none, GUILayout.Width(20)))
{
Application.OpenURL("https://docs-multiplayer.unity3d.com/netcode/current/relay/");
}
GUILayout.EndHorizontal();
EditorPrefs.SetBool(k_UseEasyRelayIntegrationKey, useRelay);
if (useRelay && !Application.isPlaying && !CloudProjectSettings.projectBound)
{
EditorGUILayout.HelpBox("To use relay, you need to setup your project in the Project Settings in the Services section.", MessageType.Warning);
if (GUILayout.Button("Open Project settings"))
{
SettingsService.OpenProjectSettings("Project/Services");
}
}
#else
var useRelay = false;
#endif
string buttonDisabledReasonSuffix = "";
if (!EditorApplication.isPlaying)
{
buttonDisabledReasonSuffix = ". This can only be done in play mode";
GUI.enabled = false;
}
if (useRelay)
{
ShowStartConnectionButtons_Relay(buttonDisabledReasonSuffix);
}
else
{
ShowStartConnectionButtons_Standard(buttonDisabledReasonSuffix);
}
if (!EditorApplication.isPlaying)
{
GUI.enabled = true;
}
}
private void ShowStartConnectionButtons_Relay(string buttonDisabledReasonSuffix)
{
#if RELAY_INTEGRATION_AVAILABLE
void AddStartServerOrHostButton(bool isServer)
{
var type = isServer ? "Server" : "Host";
if (GUILayout.Button(new GUIContent($"Start {type}", $"Starts a {type} instance with Relay{buttonDisabledReasonSuffix}")))
{
m_StartConnectionError = null;
RunNextFrame(async () =>
{
try
{
var (joinCode, allocation) = isServer ? await m_NetworkManager.StartServerWithRelay() : await m_NetworkManager.StartHostWithRelay();
m_JoinCode = joinCode;
m_Region = allocation.Region;
Repaint();
}
catch (Exception e)
{
m_StartConnectionError = e.Message;
throw;
}
});
}
}
AddStartServerOrHostButton(isServer: true);
AddStartServerOrHostButton(isServer: false);
GUILayout.Space(8f);
m_JoinCode = EditorGUILayout.TextField("Relay Join Code", m_JoinCode);
if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance with Relay" + buttonDisabledReasonSuffix)))
{
m_StartConnectionError = null;
RunNextFrame(async () =>
{
if (string.IsNullOrEmpty(m_JoinCode))
{
m_StartConnectionError = "Please provide a join code!";
return;
}
try
{
var allocation = await m_NetworkManager.StartClientWithRelay(m_JoinCode);
m_Region = allocation.Region;
Repaint();
}
catch (Exception e)
{
m_StartConnectionError = e.Message;
throw;
}
});
}
if (Application.isPlaying && !string.IsNullOrEmpty(m_StartConnectionError))
{
EditorGUILayout.HelpBox(m_StartConnectionError, MessageType.Error);
}
#endif
}
private void ShowStartConnectionButtons_Standard(string buttonDisabledReasonSuffix)
{
if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix)))
{
m_NetworkManager.StartHost();
}
if (GUILayout.Button(new GUIContent("Start Server", "Starts a server instance" + buttonDisabledReasonSuffix)))
{
m_NetworkManager.StartServer();
}
if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix)))
{
m_NetworkManager.StartClient();
}
}
private void DrawDisconnectButton()
{
string instanceType = string.Empty;
if (m_NetworkManager.IsHost)
{
instanceType = "Host";
}
else if (m_NetworkManager.IsServer)
{
instanceType = "Server";
}
else if (m_NetworkManager.IsClient)
{
instanceType = "Client";
}
EditorGUILayout.HelpBox($"You cannot edit the NetworkConfig when a {instanceType} is running.", MessageType.Info);
#if RELAY_INTEGRATION_AVAILABLE
if (!string.IsNullOrEmpty(m_JoinCode) && !string.IsNullOrEmpty(m_Region))
{
var style = new GUIStyle(EditorStyles.helpBox)
{
fontSize = 10,
alignment = TextAnchor.MiddleCenter,
};
GUILayout.BeginHorizontal(style, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false), GUILayout.MaxWidth(800));
GUILayout.Label(new GUIContent(EditorGUIUtility.IconContent(k_InfoIconName)), GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(true));
GUILayout.Space(25f);
GUILayout.BeginVertical();
GUILayout.Space(4f);
GUILayout.Label($"Connected via relay ({m_Region}).\nJoin code: {m_JoinCode}", EditorStyles.miniLabel, GUILayout.ExpandHeight(true));
if (GUILayout.Button("Copy code", GUILayout.ExpandHeight(true)))
{
GUIUtility.systemCopyBuffer = m_JoinCode;
}
GUILayout.Space(4f);
GUILayout.EndVertical();
GUILayout.Space(2f);
GUILayout.EndHorizontal();
}
#endif
if (GUILayout.Button(new GUIContent($"Stop {instanceType}", $"Stops the {instanceType} instance.")))
{
#if RELAY_INTEGRATION_AVAILABLE
m_JoinCode = "";
#endif
m_NetworkManager.Shutdown();
}
}
private const string k_InfoIconName = "console.infoicon";
private static void DrawInstallMultiplayerToolsTip()
{
const string getToolsText = "Access additional tools for multiplayer development by installing the Multiplayer Tools package in the Package Manager.";
const string openDocsButtonText = "Open Docs";
const string dismissButtonText = "Dismiss";
const string targetUrl = "https://docs-multiplayer.unity3d.com/tools/current/install-tools";
const string infoIconName = "console.infoicon";
if (NetcodeForGameObjectsEditorSettings.GetNetcodeInstallMultiplayerToolTips() != 0)
{
@@ -371,7 +497,7 @@ namespace Unity.Netcode.Editor
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal(s_HelpBoxStyle, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false), GUILayout.MaxWidth(800));
{
GUILayout.Label(new GUIContent(EditorGUIUtility.IconContent(infoIconName)), GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(true));
GUILayout.Label(new GUIContent(EditorGUIUtility.IconContent(k_InfoIconName)), GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(true));
GUILayout.Space(4);
GUILayout.Label(getToolsText, s_CenteredWordWrappedLabelStyle, GUILayout.ExpandHeight(true));
@@ -404,5 +530,69 @@ namespace Unity.Netcode.Editor
GUILayout.Space(10);
}
private void DrawPrefabListField()
{
if (!m_NetworkManager.NetworkConfig.HasOldPrefabList())
{
if (m_NetworkManager.NetworkConfig.Prefabs.NetworkPrefabsLists.Count == 0)
{
EditorGUILayout.HelpBox("You have no prefab list selected. You will have to add your prefabs manually at runtime for netcode to work.", MessageType.Warning);
}
EditorGUILayout.PropertyField(m_PrefabsList);
return;
}
// Old format of prefab list
EditorGUILayout.HelpBox("Network Prefabs serialized in old format. Migrate to new format to edit the list.", MessageType.Info);
if (GUILayout.Button(new GUIContent("Migrate Prefab List", "Converts the old format Network Prefab list to a new Scriptable Object")))
{
// Default directory
var directory = "Assets/";
var assetPath = AssetDatabase.GetAssetPath(m_NetworkManager);
if (assetPath == "")
{
assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(m_NetworkManager);
}
if (assetPath != "")
{
directory = Path.GetDirectoryName(assetPath);
}
else
{
#if UNITY_2021_1_OR_NEWER
var prefabStage = UnityEditor.SceneManagement.PrefabStageUtility.GetPrefabStage(m_NetworkManager.gameObject);
#else
var prefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetPrefabStage(m_NetworkManager.gameObject);
#endif
if (prefabStage != null)
{
var prefabPath = prefabStage.assetPath;
if (!string.IsNullOrEmpty(prefabPath))
{
directory = Path.GetDirectoryName(prefabPath);
}
}
if (m_NetworkManager.gameObject.scene != null)
{
var scenePath = m_NetworkManager.gameObject.scene.path;
if (!string.IsNullOrEmpty(scenePath))
{
directory = Path.GetDirectoryName(scenePath);
}
}
}
var networkPrefabs = m_NetworkManager.NetworkConfig.MigrateOldNetworkPrefabsToNetworkPrefabsList();
string path = Path.Combine(directory, $"NetworkPrefabs-{m_NetworkManager.GetInstanceID()}.asset");
Debug.Log("Saving migrated Network Prefabs List to " + path);
AssetDatabase.CreateAsset(networkPrefabs, path);
EditorUtility.SetDirty(m_NetworkManager);
}
}
}
}

View File

@@ -0,0 +1,120 @@
#if UNITY_2022_3_OR_NEWER && (RELAY_SDK_INSTALLED && !UNITY_WEBGL ) || (RELAY_SDK_INSTALLED && UNITY_WEBGL && UTP_TRANSPORT_2_0_ABOVE)
using System;
using System.Threading.Tasks;
using Unity.Netcode.Transports.UTP;
using Unity.Networking.Transport.Relay;
using Unity.Services.Authentication;
using Unity.Services.Core;
using Unity.Services.Relay;
using Unity.Services.Relay.Models;
namespace Unity.Netcode.Editor
{
/// <summary>
/// Integration with Unity Relay SDK and Unity Transport that support the additional buttons in the NetworkManager inspector.
/// This code could theoretically be used at runtime, but we would like to avoid the additional dependencies in the runtime assembly of netcode for gameobjects.
/// </summary>
public static class NetworkManagerRelayIntegration
{
#if UNITY_WEBGL
private const string k_DefaultConnectionType = "wss";
#else
private const string k_DefaultConnectionType = "dtls";
#endif
/// <summary>
/// Easy relay integration (host): it will initialize the unity services, sign in anonymously and start the host with a new relay allocation.
/// Note that this will force the use of Unity Transport.
/// </summary>
/// <param name="networkManager">The network manager that will start the connection</param>
/// <param name="maxConnections">Maximum number of connections to the created relay.</param>
/// <param name="connectionType">The connection type of the <see cref="RelayServerData"/> (wss, ws, dtls or udp) </param>
/// <returns>The join code that a potential client can use and the allocation</returns>
/// <exception cref="ServicesInitializationException"> Exception when there's an error during services initialization </exception>
/// <exception cref="UnityProjectNotLinkedException"> Exception when the project is not linked to a cloud project id </exception>
/// <exception cref="CircularDependencyException"> Exception when two registered <see cref="IInitializablePackage"/> depend on the other </exception>
/// <exception cref="AuthenticationException"> The task fails with the exception when the task cannot complete successfully due to Authentication specific errors. </exception>
/// <exception cref="RequestFailedException"> See <see cref="IAuthenticationService.SignInAnonymouslyAsync"/></exception>
/// <exception cref="ArgumentException">Thrown when the maxConnections argument fails validation in Relay Service SDK.</exception>
/// <exception cref="RelayServiceException">Thrown when the request successfully reach the Relay Allocation Service but results in an error.</exception>
internal static async Task<(string, Allocation)> StartHostWithRelay(this NetworkManager networkManager, int maxConnections = 5)
{
var codeAndAllocation = await InitializeAndCreateAllocAsync(networkManager, maxConnections, k_DefaultConnectionType);
return networkManager.StartHost() ? codeAndAllocation : (null, null);
}
/// <summary>
/// Easy relay integration (server): it will initialize the unity services, sign in anonymously and start the server with a new relay allocation.
/// Note that this will force the use of Unity Transport.
/// </summary>
/// <param name="networkManager">The network manager that will start the connection</param>
/// <param name="maxConnections">Maximum number of connections to the created relay.</param>
/// <returns>The join code that a potential client can use and the allocation.</returns>
/// <exception cref="ServicesInitializationException"> Exception when there's an error during services initialization </exception>
/// <exception cref="UnityProjectNotLinkedException"> Exception when the project is not linked to a cloud project id </exception>
/// <exception cref="CircularDependencyException"> Exception when two registered <see cref="IInitializablePackage"/> depend on the other </exception>
/// <exception cref="AuthenticationException"> The task fails with the exception when the task cannot complete successfully due to Authentication specific errors. </exception>
/// <exception cref="RequestFailedException"> See <see cref="IAuthenticationService.SignInAnonymouslyAsync"/></exception>
/// <exception cref="ArgumentException">Thrown when the maxConnections argument fails validation in Relay Service SDK.</exception>
/// <exception cref="RelayServiceException">Thrown when the request successfully reach the Relay Allocation Service but results in an error.</exception>
internal static async Task<(string, Allocation)> StartServerWithRelay(this NetworkManager networkManager, int maxConnections = 5)
{
var codeAndAllocation = await InitializeAndCreateAllocAsync(networkManager, maxConnections, k_DefaultConnectionType);
return networkManager.StartServer() ? codeAndAllocation : (null, null);
}
/// <summary>
/// Easy relay integration (client): it will initialize the unity services, sign in anonymously, join the relay with the given join code and start the client.
/// Note that this will force the use of Unity Transport.
/// </summary>
/// <param name="networkManager">The network manager that will start the connection</param>
/// <param name="joinCode">The join code of the allocation</param>
/// <exception cref="ServicesInitializationException"> Exception when there's an error during services initialization </exception>
/// <exception cref="UnityProjectNotLinkedException"> Exception when the project is not linked to a cloud project id </exception>
/// <exception cref="CircularDependencyException"> Exception when two registered <see cref="IInitializablePackage"/> depend on the other </exception>
/// <exception cref="AuthenticationException"> The task fails with the exception when the task cannot complete successfully due to Authentication specific errors. </exception>
/// <exception cref="RequestFailedException">Thrown when the request does not reach the Relay Allocation Service.</exception>
/// <exception cref="ArgumentException">Thrown if the joinCode has the wrong format.</exception>
/// <exception cref="RelayServiceException">Thrown when the request successfully reach the Relay Allocation Service but results in an error.</exception>
/// <returns>True if starting the client was successful</returns>
internal static async Task<JoinAllocation> StartClientWithRelay(this NetworkManager networkManager, string joinCode)
{
await UnityServices.InitializeAsync();
if (!AuthenticationService.Instance.IsSignedIn)
{
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
var joinAllocation = await RelayService.Instance.JoinAllocationAsync(joinCode: joinCode);
GetUnityTransport(networkManager, k_DefaultConnectionType).SetRelayServerData(new RelayServerData(joinAllocation, k_DefaultConnectionType));
return networkManager.StartClient() ? joinAllocation : null;
}
private static async Task<(string, Allocation)> InitializeAndCreateAllocAsync(NetworkManager networkManager, int maxConnections, string connectionType)
{
await UnityServices.InitializeAsync();
if (!AuthenticationService.Instance.IsSignedIn)
{
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
Allocation allocation = await RelayService.Instance.CreateAllocationAsync(maxConnections);
GetUnityTransport(networkManager, connectionType).SetRelayServerData(new RelayServerData(allocation, connectionType));
var joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
return (joinCode, allocation);
}
private static UnityTransport GetUnityTransport(NetworkManager networkManager, string connectionType)
{
if (!networkManager.TryGetComponent<UnityTransport>(out var transport))
{
transport = networkManager.gameObject.AddComponent<UnityTransport>();
}
#if UTP_TRANSPORT_2_0_ABOVE
transport.UseWebSockets = connectionType.StartsWith("ws"); // Probably should be part of SetRelayServerData, but not possible at this point
#endif
networkManager.NetworkConfig.NetworkTransport = transport; // Force using UnityTransport
return transport;
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 23b658b1c2e443109a8a131ef3632c9b
timeCreated: 1698673251

View File

@@ -10,6 +10,7 @@ namespace Unity.Netcode.Editor
[CustomEditor(typeof(NetworkTransform), true)]
public class NetworkTransformEditor : UnityEditor.Editor
{
private SerializedProperty m_UseUnreliableDeltas;
private SerializedProperty m_SyncPositionXProperty;
private SerializedProperty m_SyncPositionYProperty;
private SerializedProperty m_SyncPositionZProperty;
@@ -39,6 +40,7 @@ namespace Unity.Netcode.Editor
/// <inheritdoc/>
public void OnEnable()
{
m_UseUnreliableDeltas = serializedObject.FindProperty(nameof(NetworkTransform.UseUnreliableDeltas));
m_SyncPositionXProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionX));
m_SyncPositionYProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionY));
m_SyncPositionZProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionZ));
@@ -129,7 +131,9 @@ namespace Unity.Netcode.Editor
EditorGUILayout.PropertyField(m_PositionThresholdProperty);
EditorGUILayout.PropertyField(m_RotAngleThresholdProperty);
EditorGUILayout.PropertyField(m_ScaleThresholdProperty);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Delivery", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_UseUnreliableDeltas);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Configurations", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_InLocalSpaceProperty);

View File

@@ -3,11 +3,21 @@
"rootNamespace": "Unity.Netcode.Editor",
"references": [
"Unity.Netcode.Runtime",
"Unity.Netcode.Components"
"Unity.Netcode.Components",
"Unity.Services.Relay",
"Unity.Networking.Transport",
"Unity.Services.Core",
"Unity.Services.Authentication"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.multiplayer.tools",
@@ -33,6 +43,17 @@
"name": "com.unity.modules.physics2d",
"expression": "",
"define": "COM_UNITY_MODULES_PHYSICS2D"
},
{
"name": "com.unity.services.relay",
"expression": "1.0",
"define": "RELAY_SDK_INSTALLED"
},
{
"name": "com.unity.transport",
"expression": "2.0",
"define": "UTP_TRANSPORT_2_0_ABOVE"
}
]
}
],
"noEngineReferences": false
}