com.unity.netcode.gameobjects@2.0.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).

## [2.0.0] - 2024-09-12

### Added

- Added tooltips for all of the `NetworkObject` component's properties. (#3052)
- Added message size validation to named and unnamed message sending functions for better error messages. (#3049)
- Added "Check for NetworkObject Component" property to the Multiplayer->Netcode for GameObjects project settings. When disabled, this will bypass the in-editor `NetworkObject` check on `NetworkBehaviour` components. (#3031)
- Added `NetworkTransform.SwitchTransformSpaceWhenParented` property that, when enabled, will handle the world to local, local to world, and local to local transform space transitions when interpolation is enabled. (#3013)
- Added `NetworkTransform.TickSyncChildren` that, when enabled, will tick synchronize nested and/or child `NetworkTransform` components to eliminate any potential visual jittering that could occur if the `NetworkTransform` instances get into a state where their state updates are landing on different network ticks. (#3013)
- Added `NetworkObject.AllowOwnerToParent` property to provide the ability to allow clients to parent owned objects when running in a client-server network topology. (#3013)
- Added `NetworkObject.SyncOwnerTransformWhenParented` property to provide a way to disable applying the server's transform information in the parenting message on the client owner instance which can be useful for owner authoritative motion models. (#3013)
- Added `NetcodeEditorBase` editor helper class to provide easier modification and extension of the SDK's components. (#3013)

### Fixed

- Fixed issue where `NetworkAnimator` would send updates to non-observer clients. (#3057)
- Fixed issue where an exception could occur when receiving a universal RPC for a `NetworkObject` that has been despawned. (#3052)
- Fixed issue where a NetworkObject hidden from a client that is then promoted to be session owner was not being synchronized with newly joining clients.(#3051)
- Fixed issue where clients could have a wrong time delta on `NetworkVariableBase` which could prevent from sending delta state updates. (#3045)
- Fixed issue where setting a prefab hash value during connection approval but not having a player prefab assigned could cause an exception when spawning a player. (#3042)
- Fixed issue where the `NetworkSpawnManager.HandleNetworkObjectShow` could throw an exception if one of the `NetworkObject` components to show was destroyed during the same frame. (#3030)
- Fixed issue where the `NetworkManagerHelper` was continuing to check for hierarchy changes when in play mode. (#3026)
- Fixed issue with newly/late joined clients and `NetworkTransform` synchronization of parented `NetworkObject` instances. (#3013)
- Fixed issue with smooth transitions between transform spaces when interpolation is enabled (requires `NetworkTransform.SwitchTransformSpaceWhenParented` to be enabled). (#3013)

### Changed

- Changed `NetworkTransformEditor` now uses `NetworkTransform` as the base type class to assure it doesn't display a foldout group when using the base `NetworkTransform` component class. (#3052)
- Changed `NetworkAnimator.Awake` is now a protected virtual method. (#3052)
- Changed  when invoking `NetworkManager.ConnectionManager.DisconnectClient` during a distributed authority session a more appropriate message is logged. (#3052)
- Changed `NetworkTransformEditor` so it now derives from `NetcodeEditorBase`. (#3013)
- Changed `NetworkRigidbodyBaseEditor` so it now derives from `NetcodeEditorBase`. (#3013)
- Changed `NetworkManagerEditor` so it now derives from `NetcodeEditorBase`. (#3013)
This commit is contained in:
Unity Technologies
2024-09-12 00:00:00 +00:00
parent eab996f3ac
commit 48c6a6121c
46 changed files with 1987 additions and 492 deletions

View File

@@ -6,6 +6,41 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com). Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
## [2.0.0] - 2024-09-12
### Added
- Added tooltips for all of the `NetworkObject` component's properties. (#3052)
- Added message size validation to named and unnamed message sending functions for better error messages. (#3049)
- Added "Check for NetworkObject Component" property to the Multiplayer->Netcode for GameObjects project settings. When disabled, this will bypass the in-editor `NetworkObject` check on `NetworkBehaviour` components. (#3031)
- Added `NetworkTransform.SwitchTransformSpaceWhenParented` property that, when enabled, will handle the world to local, local to world, and local to local transform space transitions when interpolation is enabled. (#3013)
- Added `NetworkTransform.TickSyncChildren` that, when enabled, will tick synchronize nested and/or child `NetworkTransform` components to eliminate any potential visual jittering that could occur if the `NetworkTransform` instances get into a state where their state updates are landing on different network ticks. (#3013)
- Added `NetworkObject.AllowOwnerToParent` property to provide the ability to allow clients to parent owned objects when running in a client-server network topology. (#3013)
- Added `NetworkObject.SyncOwnerTransformWhenParented` property to provide a way to disable applying the server's transform information in the parenting message on the client owner instance which can be useful for owner authoritative motion models. (#3013)
- Added `NetcodeEditorBase` editor helper class to provide easier modification and extension of the SDK's components. (#3013)
### Fixed
- Fixed issue where `NetworkAnimator` would send updates to non-observer clients. (#3057)
- Fixed issue where an exception could occur when receiving a universal RPC for a `NetworkObject` that has been despawned. (#3052)
- Fixed issue where a NetworkObject hidden from a client that is then promoted to be session owner was not being synchronized with newly joining clients.(#3051)
- Fixed issue where clients could have a wrong time delta on `NetworkVariableBase` which could prevent from sending delta state updates. (#3045)
- Fixed issue where setting a prefab hash value during connection approval but not having a player prefab assigned could cause an exception when spawning a player. (#3042)
- Fixed issue where the `NetworkSpawnManager.HandleNetworkObjectShow` could throw an exception if one of the `NetworkObject` components to show was destroyed during the same frame. (#3030)
- Fixed issue where the `NetworkManagerHelper` was continuing to check for hierarchy changes when in play mode. (#3026)
- Fixed issue with newly/late joined clients and `NetworkTransform` synchronization of parented `NetworkObject` instances. (#3013)
- Fixed issue with smooth transitions between transform spaces when interpolation is enabled (requires `NetworkTransform.SwitchTransformSpaceWhenParented` to be enabled). (#3013)
### Changed
- Changed `NetworkTransformEditor` now uses `NetworkTransform` as the base type class to assure it doesn't display a foldout group when using the base `NetworkTransform` component class. (#3052)
- Changed `NetworkAnimator.Awake` is now a protected virtual method. (#3052)
- Changed when invoking `NetworkManager.ConnectionManager.DisconnectClient` during a distributed authority session a more appropriate message is logged. (#3052)
- Changed `NetworkTransformEditor` so it now derives from `NetcodeEditorBase`. (#3013)
- Changed `NetworkRigidbodyBaseEditor` so it now derives from `NetcodeEditorBase`. (#3013)
- Changed `NetworkManagerEditor` so it now derives from `NetcodeEditorBase`. (#3013)
## [2.0.0-pre.4] - 2024-08-21 ## [2.0.0-pre.4] - 2024-08-21
### Added ### Added

View File

@@ -5,6 +5,7 @@ namespace Unity.Netcode.Editor.Configuration
internal class NetcodeForGameObjectsEditorSettings internal class NetcodeForGameObjectsEditorSettings
{ {
internal const string AutoAddNetworkObjectIfNoneExists = "AutoAdd-NetworkObject-When-None-Exist"; internal const string AutoAddNetworkObjectIfNoneExists = "AutoAdd-NetworkObject-When-None-Exist";
internal const string CheckForNetworkObject = "NetworkBehaviour-Check-For-NetworkObject";
internal const string InstallMultiplayerToolsTipDismissedPlayerPrefKey = "Netcode_Tip_InstallMPTools_Dismissed"; internal const string InstallMultiplayerToolsTipDismissedPlayerPrefKey = "Netcode_Tip_InstallMPTools_Dismissed";
internal static int GetNetcodeInstallMultiplayerToolTips() internal static int GetNetcodeInstallMultiplayerToolTips()
@@ -28,7 +29,7 @@ namespace Unity.Netcode.Editor.Configuration
{ {
return EditorPrefs.GetBool(AutoAddNetworkObjectIfNoneExists); return EditorPrefs.GetBool(AutoAddNetworkObjectIfNoneExists);
} }
// Default for this is false
return false; return false;
} }
@@ -36,5 +37,20 @@ namespace Unity.Netcode.Editor.Configuration
{ {
EditorPrefs.SetBool(AutoAddNetworkObjectIfNoneExists, autoAddSetting); EditorPrefs.SetBool(AutoAddNetworkObjectIfNoneExists, autoAddSetting);
} }
internal static bool GetCheckForNetworkObjectSetting()
{
if (EditorPrefs.HasKey(CheckForNetworkObject))
{
return EditorPrefs.GetBool(CheckForNetworkObject);
}
// Default for this is true
return true;
}
internal static void SetCheckForNetworkObjectSetting(bool checkForNetworkObject)
{
EditorPrefs.SetBool(CheckForNetworkObject, checkForNetworkObject);
}
} }
} }

View File

@@ -81,6 +81,7 @@ namespace Unity.Netcode.Editor.Configuration
internal static NetcodeSettingsLabel NetworkObjectsSectionLabel; internal static NetcodeSettingsLabel NetworkObjectsSectionLabel;
internal static NetcodeSettingsToggle AutoAddNetworkObjectToggle; internal static NetcodeSettingsToggle AutoAddNetworkObjectToggle;
internal static NetcodeSettingsToggle CheckForNetworkObjectToggle;
internal static NetcodeSettingsLabel MultiplayerToolsLabel; internal static NetcodeSettingsLabel MultiplayerToolsLabel;
internal static NetcodeSettingsToggle MultiplayerToolTipStatusToggle; internal static NetcodeSettingsToggle MultiplayerToolTipStatusToggle;
@@ -103,6 +104,11 @@ namespace Unity.Netcode.Editor.Configuration
AutoAddNetworkObjectToggle = new NetcodeSettingsToggle("Auto-Add NetworkObject Component", "When enabled, NetworkObject components are automatically added to GameObjects when NetworkBehaviour components are added first.", 20); AutoAddNetworkObjectToggle = new NetcodeSettingsToggle("Auto-Add NetworkObject Component", "When enabled, NetworkObject components are automatically added to GameObjects when NetworkBehaviour components are added first.", 20);
} }
if (CheckForNetworkObjectToggle == null)
{
CheckForNetworkObjectToggle = new NetcodeSettingsToggle("Check for NetworkObject Component", "When disabled, the automatic check on NetworkBehaviours for an associated NetworkObject component will not be performed and Auto-Add NetworkObject Component will be disabled.", 20);
}
if (MultiplayerToolsLabel == null) if (MultiplayerToolsLabel == null)
{ {
MultiplayerToolsLabel = new NetcodeSettingsLabel("Multiplayer Tools", 20); MultiplayerToolsLabel = new NetcodeSettingsLabel("Multiplayer Tools", 20);
@@ -120,7 +126,9 @@ namespace Unity.Netcode.Editor.Configuration
CheckForInitialize(); CheckForInitialize();
var autoAddNetworkObjectSetting = NetcodeForGameObjectsEditorSettings.GetAutoAddNetworkObjectSetting(); var autoAddNetworkObjectSetting = NetcodeForGameObjectsEditorSettings.GetAutoAddNetworkObjectSetting();
var checkForNetworkObjectSetting = NetcodeForGameObjectsEditorSettings.GetCheckForNetworkObjectSetting();
var multiplayerToolsTipStatus = NetcodeForGameObjectsEditorSettings.GetNetcodeInstallMultiplayerToolTips() == 0; var multiplayerToolsTipStatus = NetcodeForGameObjectsEditorSettings.GetNetcodeInstallMultiplayerToolTips() == 0;
var settings = NetcodeForGameObjectsProjectSettings.instance; var settings = NetcodeForGameObjectsProjectSettings.instance;
var generateDefaultPrefabs = settings.GenerateDefaultNetworkPrefabs; var generateDefaultPrefabs = settings.GenerateDefaultNetworkPrefabs;
var networkPrefabsPath = settings.TempNetworkPrefabsPath; var networkPrefabsPath = settings.TempNetworkPrefabsPath;
@@ -134,7 +142,13 @@ namespace Unity.Netcode.Editor.Configuration
{ {
GUILayout.BeginVertical("Box"); GUILayout.BeginVertical("Box");
NetworkObjectsSectionLabel.DrawLabel(); NetworkObjectsSectionLabel.DrawLabel();
autoAddNetworkObjectSetting = AutoAddNetworkObjectToggle.DrawToggle(autoAddNetworkObjectSetting);
autoAddNetworkObjectSetting = AutoAddNetworkObjectToggle.DrawToggle(autoAddNetworkObjectSetting, checkForNetworkObjectSetting);
checkForNetworkObjectSetting = CheckForNetworkObjectToggle.DrawToggle(checkForNetworkObjectSetting);
if (autoAddNetworkObjectSetting && !checkForNetworkObjectSetting)
{
autoAddNetworkObjectSetting = false;
}
GUILayout.EndVertical(); GUILayout.EndVertical();
GUILayout.BeginVertical("Box"); GUILayout.BeginVertical("Box");
@@ -184,6 +198,7 @@ namespace Unity.Netcode.Editor.Configuration
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
NetcodeForGameObjectsEditorSettings.SetAutoAddNetworkObjectSetting(autoAddNetworkObjectSetting); NetcodeForGameObjectsEditorSettings.SetAutoAddNetworkObjectSetting(autoAddNetworkObjectSetting);
NetcodeForGameObjectsEditorSettings.SetCheckForNetworkObjectSetting(checkForNetworkObjectSetting);
NetcodeForGameObjectsEditorSettings.SetNetcodeInstallMultiplayerToolTips(multiplayerToolsTipStatus ? 0 : 1); NetcodeForGameObjectsEditorSettings.SetNetcodeInstallMultiplayerToolTips(multiplayerToolsTipStatus ? 0 : 1);
settings.GenerateDefaultNetworkPrefabs = generateDefaultPrefabs; settings.GenerateDefaultNetworkPrefabs = generateDefaultPrefabs;
settings.TempNetworkPrefabsPath = networkPrefabsPath; settings.TempNetworkPrefabsPath = networkPrefabsPath;
@@ -213,10 +228,13 @@ namespace Unity.Netcode.Editor.Configuration
{ {
private GUIContent m_ToggleContent; private GUIContent m_ToggleContent;
public bool DrawToggle(bool currentSetting) public bool DrawToggle(bool currentSetting, bool enabled = true)
{ {
EditorGUIUtility.labelWidth = m_LabelSize; EditorGUIUtility.labelWidth = m_LabelSize;
return EditorGUILayout.Toggle(m_ToggleContent, currentSetting, m_LayoutWidth); GUI.enabled = enabled;
var returnValue = EditorGUILayout.Toggle(m_ToggleContent, currentSetting, m_LayoutWidth);
GUI.enabled = true;
return returnValue;
} }
public NetcodeSettingsToggle(string labelText, string toolTip, float layoutOffset) public NetcodeSettingsToggle(string labelText, string toolTip, float layoutOffset)

View File

@@ -0,0 +1,62 @@
using System;
using UnityEditor;
using UnityEngine;
namespace Unity.Netcode.Editor
{
/// <summary>
/// The base Netcode Editor helper class to display derived <see cref="MonoBehaviour"/> based components <br />
/// where each child generation's properties will be displayed within a FoldoutHeaderGroup.
/// </summary>
[CanEditMultipleObjects]
public partial class NetcodeEditorBase<TT> : UnityEditor.Editor where TT : MonoBehaviour
{
/// <inheritdoc/>
public virtual void OnEnable()
{
}
/// <summary>
/// Helper method to draw the properties of the specified child type <typeparamref name="T"/> component within a FoldoutHeaderGroup.
/// </summary>
/// <typeparam name="T">The specific child type that should have its properties drawn.</typeparam>
/// <param name="type">The component type of the <see cref="UnityEditor.Editor.target"/>.</param>
/// <param name="displayProperties">The <see cref="Action"/> to invoke that will draw the type <typeparamref name="T"/> properties.</param>
/// <param name="expanded">The <typeparamref name="T"/> current expanded property value</param>
/// <param name="setExpandedProperty">The <see cref="Action{bool}"/> invoked to apply the updated <paramref name="expanded"/> value.</param>
protected void DrawFoldOutGroup<T>(Type type, Action displayProperties, bool expanded, Action<bool> setExpandedProperty)
{
var baseClass = target as TT;
EditorGUI.BeginChangeCheck();
serializedObject.Update();
var currentClass = typeof(T);
if (type.IsSubclassOf(currentClass) || (!type.IsSubclassOf(currentClass) && currentClass.IsSubclassOf(typeof(TT))))
{
var expandedValue = EditorGUILayout.BeginFoldoutHeaderGroup(expanded, $"{currentClass.Name} Properties");
if (expandedValue)
{
EditorGUILayout.EndFoldoutHeaderGroup();
displayProperties.Invoke();
}
else
{
EditorGUILayout.EndFoldoutHeaderGroup();
}
EditorGUILayout.Space();
setExpandedProperty.Invoke(expandedValue);
}
else
{
displayProperties.Invoke();
}
serializedObject.ApplyModifiedProperties();
EditorGUI.EndChangeCheck();
}
/// <inheritdoc/>
public override void OnInspectorGUI()
{
serializedObject.ApplyModifiedProperties();
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4ce97256a2d80f94bb340e13c71a24b8

View File

@@ -301,9 +301,8 @@ namespace Unity.Netcode.Editor
expanded = false; expanded = false;
} }
serializedObject.ApplyModifiedProperties();
EditorGUI.EndChangeCheck(); EditorGUI.EndChangeCheck();
serializedObject.ApplyModifiedProperties();
} }
/// <summary> /// <summary>
@@ -352,6 +351,12 @@ namespace Unity.Netcode.Editor
return; return;
} }
// If this automatic check is disabled, then do not perform this check.
if (!NetcodeForGameObjectsEditorSettings.GetCheckForNetworkObjectSetting())
{
return;
}
// Now get the root parent transform to the current GameObject (or itself) // Now get the root parent transform to the current GameObject (or itself)
var rootTransform = GetRootParentTransform(gameObject.transform); var rootTransform = GetRootParentTransform(gameObject.transform);
if (!rootTransform.TryGetComponent<NetworkManager>(out var networkManager)) if (!rootTransform.TryGetComponent<NetworkManager>(out var networkManager))

View File

@@ -13,7 +13,7 @@ namespace Unity.Netcode.Editor
/// </summary> /// </summary>
[CustomEditor(typeof(NetworkManager), true)] [CustomEditor(typeof(NetworkManager), true)]
[CanEditMultipleObjects] [CanEditMultipleObjects]
public class NetworkManagerEditor : UnityEditor.Editor public class NetworkManagerEditor : NetcodeEditorBase<NetworkManager>
{ {
private static GUIStyle s_CenteredWordWrappedLabelStyle; private static GUIStyle s_CenteredWordWrappedLabelStyle;
private static GUIStyle s_HelpBoxStyle; private static GUIStyle s_HelpBoxStyle;
@@ -168,16 +168,8 @@ namespace Unity.Netcode.Editor
.FindPropertyRelative(nameof(NetworkPrefabs.NetworkPrefabsLists)); .FindPropertyRelative(nameof(NetworkPrefabs.NetworkPrefabsLists));
} }
/// <inheritdoc/> private void DisplayNetworkManagerProperties()
public override void OnInspectorGUI()
{ {
Initialize();
CheckNullProperties();
#if !MULTIPLAYER_TOOLS
DrawInstallMultiplayerToolsTip();
#endif
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient) if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
{ {
serializedObject.Update(); serializedObject.Update();
@@ -298,9 +290,12 @@ namespace Unity.Netcode.Editor
} }
serializedObject.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties();
}
}
private void DisplayCallToActionButtons()
// Start buttons below {
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
{ {
string buttonDisabledReasonSuffix = ""; string buttonDisabledReasonSuffix = "";
@@ -341,7 +336,6 @@ namespace Unity.Netcode.Editor
GUI.enabled = true; GUI.enabled = true;
} }
} }
}
else else
{ {
string instanceType = string.Empty; string instanceType = string.Empty;
@@ -368,6 +362,21 @@ namespace Unity.Netcode.Editor
} }
} }
/// <inheritdoc/>
public override void OnInspectorGUI()
{
var networkManager = target as NetworkManager;
Initialize();
CheckNullProperties();
#if !MULTIPLAYER_TOOLS
DrawInstallMultiplayerToolsTip();
#endif
void SetExpanded(bool expanded) { networkManager.NetworkManagerExpanded = expanded; };
DrawFoldOutGroup<NetworkManager>(networkManager.GetType(), DisplayNetworkManagerProperties, networkManager.NetworkManagerExpanded, SetExpanded);
DisplayCallToActionButtons();
base.OnInspectorGUI();
}
private static void DrawInstallMultiplayerToolsTip() 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 getToolsText = "Access additional tools for multiplayer development by installing the Multiplayer Tools package in the Package Manager.";

View File

@@ -61,6 +61,12 @@ namespace Unity.Netcode.Editor
{ {
s_LastKnownNetworkManagerParents.Clear(); s_LastKnownNetworkManagerParents.Clear();
ScenesInBuildActiveSceneCheck(); ScenesInBuildActiveSceneCheck();
EditorApplication.hierarchyChanged -= EditorApplication_hierarchyChanged;
break;
}
case PlayModeStateChange.EnteredEditMode:
{
EditorApplication.hierarchyChanged += EditorApplication_hierarchyChanged;
break; break;
} }
} }
@@ -110,6 +116,12 @@ namespace Unity.Netcode.Editor
/// </summary> /// </summary>
private static void EditorApplication_hierarchyChanged() private static void EditorApplication_hierarchyChanged()
{ {
if (Application.isPlaying)
{
EditorApplication.hierarchyChanged -= EditorApplication_hierarchyChanged;
return;
}
var allNetworkManagers = Resources.FindObjectsOfTypeAll<NetworkManager>(); var allNetworkManagers = Resources.FindObjectsOfTypeAll<NetworkManager>();
foreach (var networkManager in allNetworkManagers) foreach (var networkManager in allNetworkManagers)
{ {

View File

@@ -0,0 +1,42 @@
#if COM_UNITY_MODULES_PHYSICS || COM_UNITY_MODULES_PHYSICS2D
using Unity.Netcode.Components;
using UnityEditor;
namespace Unity.Netcode.Editor
{
[CustomEditor(typeof(NetworkRigidbodyBase), true)]
[CanEditMultipleObjects]
public class NetworkRigidbodyBaseEditor : NetcodeEditorBase<NetworkBehaviour>
{
private SerializedProperty m_UseRigidBodyForMotion;
private SerializedProperty m_AutoUpdateKinematicState;
private SerializedProperty m_AutoSetKinematicOnDespawn;
public override void OnEnable()
{
m_UseRigidBodyForMotion = serializedObject.FindProperty(nameof(NetworkRigidbodyBase.UseRigidBodyForMotion));
m_AutoUpdateKinematicState = serializedObject.FindProperty(nameof(NetworkRigidbodyBase.AutoUpdateKinematicState));
m_AutoSetKinematicOnDespawn = serializedObject.FindProperty(nameof(NetworkRigidbodyBase.AutoSetKinematicOnDespawn));
base.OnEnable();
}
private void DisplayNetworkRigidbodyProperties()
{
EditorGUILayout.PropertyField(m_UseRigidBodyForMotion);
EditorGUILayout.PropertyField(m_AutoUpdateKinematicState);
EditorGUILayout.PropertyField(m_AutoSetKinematicOnDespawn);
}
/// <inheritdoc/>
public override void OnInspectorGUI()
{
var networkRigidbodyBase = target as NetworkRigidbodyBase;
void SetExpanded(bool expanded) { networkRigidbodyBase.NetworkRigidbodyBaseExpanded = expanded; };
DrawFoldOutGroup<NetworkRigidbodyBase>(networkRigidbodyBase.GetType(), DisplayNetworkRigidbodyProperties, networkRigidbodyBase.NetworkRigidbodyBaseExpanded, SetExpanded);
base.OnInspectorGUI();
}
}
}
#endif

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 06561c57f81a6354f8bb16076f1de3a9

View File

@@ -8,8 +8,11 @@ namespace Unity.Netcode.Editor
/// The <see cref="CustomEditor"/> for <see cref="NetworkTransform"/> /// The <see cref="CustomEditor"/> for <see cref="NetworkTransform"/>
/// </summary> /// </summary>
[CustomEditor(typeof(NetworkTransform), true)] [CustomEditor(typeof(NetworkTransform), true)]
public class NetworkTransformEditor : UnityEditor.Editor [CanEditMultipleObjects]
public class NetworkTransformEditor : NetcodeEditorBase<NetworkTransform>
{ {
private SerializedProperty m_SwitchTransformSpaceWhenParented;
private SerializedProperty m_TickSyncChildren;
private SerializedProperty m_UseUnreliableDeltas; private SerializedProperty m_UseUnreliableDeltas;
private SerializedProperty m_SyncPositionXProperty; private SerializedProperty m_SyncPositionXProperty;
private SerializedProperty m_SyncPositionYProperty; private SerializedProperty m_SyncPositionYProperty;
@@ -39,8 +42,10 @@ namespace Unity.Netcode.Editor
private static GUIContent s_ScaleLabel = EditorGUIUtility.TrTextContent("Scale"); private static GUIContent s_ScaleLabel = EditorGUIUtility.TrTextContent("Scale");
/// <inheritdoc/> /// <inheritdoc/>
public virtual void OnEnable() public override void OnEnable()
{ {
m_SwitchTransformSpaceWhenParented = serializedObject.FindProperty(nameof(NetworkTransform.SwitchTransformSpaceWhenParented));
m_TickSyncChildren = serializedObject.FindProperty(nameof(NetworkTransform.TickSyncChildren));
m_UseUnreliableDeltas = serializedObject.FindProperty(nameof(NetworkTransform.UseUnreliableDeltas)); m_UseUnreliableDeltas = serializedObject.FindProperty(nameof(NetworkTransform.UseUnreliableDeltas));
m_SyncPositionXProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionX)); m_SyncPositionXProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionX));
m_SyncPositionYProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionY)); m_SyncPositionYProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionY));
@@ -61,10 +66,10 @@ namespace Unity.Netcode.Editor
m_UseHalfFloatPrecision = serializedObject.FindProperty(nameof(NetworkTransform.UseHalfFloatPrecision)); m_UseHalfFloatPrecision = serializedObject.FindProperty(nameof(NetworkTransform.UseHalfFloatPrecision));
m_SlerpPosition = serializedObject.FindProperty(nameof(NetworkTransform.SlerpPosition)); m_SlerpPosition = serializedObject.FindProperty(nameof(NetworkTransform.SlerpPosition));
m_AuthorityMode = serializedObject.FindProperty(nameof(NetworkTransform.AuthorityMode)); m_AuthorityMode = serializedObject.FindProperty(nameof(NetworkTransform.AuthorityMode));
base.OnEnable();
} }
/// <inheritdoc/> private void DisplayNetworkTransformProperties()
public override void OnInspectorGUI()
{ {
var networkTransform = target as NetworkTransform; var networkTransform = target as NetworkTransform;
EditorGUILayout.LabelField("Axis to Synchronize", EditorStyles.boldLabel); EditorGUILayout.LabelField("Axis to Synchronize", EditorStyles.boldLabel);
@@ -141,9 +146,15 @@ namespace Unity.Netcode.Editor
EditorGUILayout.PropertyField(m_ScaleThresholdProperty); EditorGUILayout.PropertyField(m_ScaleThresholdProperty);
EditorGUILayout.Space(); EditorGUILayout.Space();
EditorGUILayout.LabelField("Delivery", EditorStyles.boldLabel); EditorGUILayout.LabelField("Delivery", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_TickSyncChildren);
EditorGUILayout.PropertyField(m_UseUnreliableDeltas); EditorGUILayout.PropertyField(m_UseUnreliableDeltas);
EditorGUILayout.Space(); EditorGUILayout.Space();
EditorGUILayout.LabelField("Configurations", EditorStyles.boldLabel); EditorGUILayout.LabelField("Configurations", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_SwitchTransformSpaceWhenParented);
if (m_SwitchTransformSpaceWhenParented.boolValue)
{
m_TickSyncChildren.boolValue = true;
}
EditorGUILayout.PropertyField(m_InLocalSpaceProperty); EditorGUILayout.PropertyField(m_InLocalSpaceProperty);
if (!networkTransform.HideInterpolateValue) if (!networkTransform.HideInterpolateValue)
{ {
@@ -163,8 +174,7 @@ namespace Unity.Netcode.Editor
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
// if rigidbody is present but network rigidbody is not present // if rigidbody is present but network rigidbody is not present
var go = ((NetworkTransform)target).gameObject; if (networkTransform.TryGetComponent<Rigidbody>(out _) && networkTransform.TryGetComponent<NetworkRigidbody>(out _) == false)
if (go.TryGetComponent<Rigidbody>(out _) && go.TryGetComponent<NetworkRigidbody>(out _) == false)
{ {
EditorGUILayout.HelpBox("This GameObject contains a Rigidbody but no NetworkRigidbody.\n" + EditorGUILayout.HelpBox("This GameObject contains a Rigidbody but no NetworkRigidbody.\n" +
"Add a NetworkRigidbody component to improve Rigidbody synchronization.", MessageType.Warning); "Add a NetworkRigidbody component to improve Rigidbody synchronization.", MessageType.Warning);
@@ -172,14 +182,23 @@ namespace Unity.Netcode.Editor
#endif // COM_UNITY_MODULES_PHYSICS #endif // COM_UNITY_MODULES_PHYSICS
#if COM_UNITY_MODULES_PHYSICS2D #if COM_UNITY_MODULES_PHYSICS2D
if (go.TryGetComponent<Rigidbody2D>(out _) && go.TryGetComponent<NetworkRigidbody2D>(out _) == false) if (networkTransform.TryGetComponent<Rigidbody2D>(out _) && networkTransform.TryGetComponent<NetworkRigidbody2D>(out _) == false)
{ {
EditorGUILayout.HelpBox("This GameObject contains a Rigidbody2D but no NetworkRigidbody2D.\n" + EditorGUILayout.HelpBox("This GameObject contains a Rigidbody2D but no NetworkRigidbody2D.\n" +
"Add a NetworkRigidbody2D component to improve Rigidbody2D synchronization.", MessageType.Warning); "Add a NetworkRigidbody2D component to improve Rigidbody2D synchronization.", MessageType.Warning);
} }
#endif // COM_UNITY_MODULES_PHYSICS2D #endif // COM_UNITY_MODULES_PHYSICS2D
}
serializedObject.ApplyModifiedProperties();
/// <inheritdoc/>
public override void OnInspectorGUI()
{
var networkTransform = target as NetworkTransform;
void SetExpanded(bool expanded) { networkTransform.NetworkTransformExpanded = expanded; };
DrawFoldOutGroup<NetworkTransform>(networkTransform.GetType(), DisplayNetworkTransformProperties, networkTransform.NetworkTransformExpanded, SetExpanded);
base.OnInspectorGUI();
} }
} }
} }

View File

@@ -239,19 +239,13 @@ namespace Unity.Netcode.Components
m_CurrentSmoothTime = 0; m_CurrentSmoothTime = 0;
} }
public override void OnUpdate() private void ProcessSmoothing()
{ {
// If not spawned or this instance has authority, exit early // If not spawned or this instance has authority, exit early
if (!IsSpawned) if (!IsSpawned)
{ {
return; return;
} }
// Do not call the base class implementation...
// AnticipatedNetworkTransform applies its authoritative state immediately rather than waiting for update
// This is because AnticipatedNetworkTransforms may need to reference each other in reanticipating
// and we will want all reanticipation done before anything else wants to reference the transform in
// OnUpdate()
//base.Update();
if (m_CurrentSmoothTime < m_SmoothDuration) if (m_CurrentSmoothTime < m_SmoothDuration)
{ {
@@ -262,7 +256,7 @@ namespace Unity.Netcode.Components
m_AnticipatedTransform = new TransformState m_AnticipatedTransform = new TransformState
{ {
Position = Vector3.Lerp(m_SmoothFrom.Position, m_SmoothTo.Position, pct), Position = Vector3.Lerp(m_SmoothFrom.Position, m_SmoothTo.Position, pct),
Rotation = Quaternion.Slerp(m_SmoothFrom.Rotation, m_SmoothTo.Rotation, pct), Rotation = Quaternion.Lerp(m_SmoothFrom.Rotation, m_SmoothTo.Rotation, pct),
Scale = Vector3.Lerp(m_SmoothFrom.Scale, m_SmoothTo.Scale, pct) Scale = Vector3.Lerp(m_SmoothFrom.Scale, m_SmoothTo.Scale, pct)
}; };
m_PreviousAnticipatedTransform = m_AnticipatedTransform; m_PreviousAnticipatedTransform = m_AnticipatedTransform;
@@ -275,6 +269,32 @@ namespace Unity.Netcode.Components
} }
} }
// TODO: This does not handle OnFixedUpdate
// This requires a complete overhaul in this class to switch between using
// NetworkRigidbody's position and rotation values.
public override void OnUpdate()
{
ProcessSmoothing();
// Do not call the base class implementation...
// AnticipatedNetworkTransform applies its authoritative state immediately rather than waiting for update
// This is because AnticipatedNetworkTransforms may need to reference each other in reanticipating
// and we will want all reanticipation done before anything else wants to reference the transform in
// OnUpdate()
//base.OnUpdate();
}
/// <summary>
/// Since authority does not subscribe to updates (OnUpdate or OnFixedUpdate),
/// we have to update every frame to assure authority processes soothing.
/// </summary>
private void Update()
{
if (CanCommitToTransform && IsSpawned)
{
ProcessSmoothing();
}
}
internal class AnticipatedObject : IAnticipationEventReceiver, IAnticipatedObject internal class AnticipatedObject : IAnticipationEventReceiver, IAnticipatedObject
{ {
public AnticipatedNetworkTransform Transform; public AnticipatedNetworkTransform Transform;
@@ -347,14 +367,44 @@ namespace Unity.Netcode.Components
m_CurrentSmoothTime = 0; m_CurrentSmoothTime = 0;
} }
protected override void OnSynchronize<T>(ref BufferSerializer<T> serializer) /// <summary>
/// (This replaces the first OnSynchronize for NetworkTransforms)
/// This is needed to initialize when fully synchronized since non-authority instances
/// don't apply the initial synchronization (new client synchronization) until after
/// everything has been spawned and synchronized.
/// </summary>
protected internal override void InternalOnNetworkSessionSynchronized()
{ {
base.OnSynchronize(ref serializer); var wasSynchronizing = SynchronizeState.IsSynchronizing;
if (!CanCommitToTransform) base.InternalOnNetworkSessionSynchronized();
if (!CanCommitToTransform && wasSynchronizing && !SynchronizeState.IsSynchronizing)
{ {
m_OutstandingAuthorityChange = true; m_OutstandingAuthorityChange = true;
ApplyAuthoritativeState(); ApplyAuthoritativeState();
ResetAnticipatedState(); ResetAnticipatedState();
m_AnticipatedObject = new AnticipatedObject { Transform = this };
NetworkManager.AnticipationSystem.RegisterForAnticipationEvents(m_AnticipatedObject);
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject);
}
}
/// <summary>
/// (This replaces the any subsequent OnSynchronize for NetworkTransforms post client synchronization)
/// This occurs on already connected clients when dynamically spawning a NetworkObject for
/// non-authoritative instances.
/// </summary>
protected internal override void InternalOnNetworkPostSpawn()
{
base.InternalOnNetworkPostSpawn();
if (!CanCommitToTransform && NetworkManager.IsConnectedClient && !SynchronizeState.IsSynchronizing)
{
m_OutstandingAuthorityChange = true;
ApplyAuthoritativeState();
ResetAnticipatedState();
m_AnticipatedObject = new AnticipatedObject { Transform = this };
NetworkManager.AnticipationSystem.RegisterForAnticipationEvents(m_AnticipatedObject);
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject);
} }
} }
@@ -365,6 +415,13 @@ namespace Unity.Netcode.Components
Debug.LogWarning($"This component is not currently supported in distributed authority."); Debug.LogWarning($"This component is not currently supported in distributed authority.");
} }
base.OnNetworkSpawn(); base.OnNetworkSpawn();
// Non-authoritative instances exit early if the synchronization has yet to
// be applied at this point
if (SynchronizeState.IsSynchronizing && !CanCommitToTransform)
{
return;
}
m_OutstandingAuthorityChange = true; m_OutstandingAuthorityChange = true;
ApplyAuthoritativeState(); ApplyAuthoritativeState();
ResetAnticipatedState(); ResetAnticipatedState();

View File

@@ -12,7 +12,7 @@ namespace Unity.Netcode
public abstract class BufferedLinearInterpolator<T> where T : struct public abstract class BufferedLinearInterpolator<T> where T : struct
{ {
internal float MaxInterpolationBound = 3.0f; internal float MaxInterpolationBound = 3.0f;
private struct BufferedItem protected internal struct BufferedItem
{ {
public T Item; public T Item;
public double TimeSent; public double TimeSent;
@@ -31,14 +31,16 @@ namespace Unity.Netcode
private const double k_SmallValue = 9.999999439624929E-11; // copied from Vector3's equal operator private const double k_SmallValue = 9.999999439624929E-11; // copied from Vector3's equal operator
private T m_InterpStartValue; protected internal T m_InterpStartValue;
private T m_CurrentInterpValue; protected internal T m_CurrentInterpValue;
private T m_InterpEndValue; protected internal T m_InterpEndValue;
private double m_EndTimeConsumed; private double m_EndTimeConsumed;
private double m_StartTimeConsumed; private double m_StartTimeConsumed;
private readonly List<BufferedItem> m_Buffer = new List<BufferedItem>(k_BufferCountLimit); protected internal readonly List<BufferedItem> m_Buffer = new List<BufferedItem>(k_BufferCountLimit);
// Buffer consumption scenarios // Buffer consumption scenarios
// Perfect case consumption // Perfect case consumption
@@ -73,6 +75,21 @@ namespace Unity.Netcode
private bool InvalidState => m_Buffer.Count == 0 && m_LifetimeConsumedCount == 0; private bool InvalidState => m_Buffer.Count == 0 && m_LifetimeConsumedCount == 0;
internal bool EndOfBuffer => m_Buffer.Count == 0;
internal bool InLocalSpace;
protected internal virtual void OnConvertTransformSpace(Transform transform, bool inLocalSpace)
{
}
internal void ConvertTransformSpace(Transform transform, bool inLocalSpace)
{
OnConvertTransformSpace(transform, inLocalSpace);
InLocalSpace = inLocalSpace;
}
/// <summary> /// <summary>
/// Resets interpolator to initial state /// Resets interpolator to initial state
/// </summary> /// </summary>
@@ -351,6 +368,35 @@ namespace Unity.Netcode
return Quaternion.Lerp(start, end, time); return Quaternion.Lerp(start, end, time);
} }
} }
private Quaternion ConvertToNewTransformSpace(Transform transform, Quaternion rotation, bool inLocalSpace)
{
if (inLocalSpace)
{
return Quaternion.Inverse(transform.rotation) * rotation;
}
else
{
return transform.rotation * rotation;
}
}
protected internal override void OnConvertTransformSpace(Transform transform, bool inLocalSpace)
{
for (int i = 0; i < m_Buffer.Count; i++)
{
var entry = m_Buffer[i];
entry.Item = ConvertToNewTransformSpace(transform, entry.Item, inLocalSpace);
m_Buffer[i] = entry;
}
m_InterpStartValue = ConvertToNewTransformSpace(transform, m_InterpStartValue, inLocalSpace);
m_CurrentInterpValue = ConvertToNewTransformSpace(transform, m_CurrentInterpValue, inLocalSpace);
m_InterpEndValue = ConvertToNewTransformSpace(transform, m_InterpEndValue, inLocalSpace);
base.OnConvertTransformSpace(transform, inLocalSpace);
}
} }
/// <summary> /// <summary>
@@ -388,5 +434,34 @@ namespace Unity.Netcode
return Vector3.Lerp(start, end, time); return Vector3.Lerp(start, end, time);
} }
} }
private Vector3 ConvertToNewTransformSpace(Transform transform, Vector3 position, bool inLocalSpace)
{
if (inLocalSpace)
{
return transform.InverseTransformPoint(position);
}
else
{
return transform.TransformPoint(position);
}
}
protected internal override void OnConvertTransformSpace(Transform transform, bool inLocalSpace)
{
for (int i = 0; i < m_Buffer.Count; i++)
{
var entry = m_Buffer[i];
entry.Item = ConvertToNewTransformSpace(transform, entry.Item, inLocalSpace);
m_Buffer[i] = entry;
}
m_InterpStartValue = ConvertToNewTransformSpace(transform, m_InterpStartValue, inLocalSpace);
m_CurrentInterpValue = ConvertToNewTransformSpace(transform, m_CurrentInterpValue, inLocalSpace);
m_InterpEndValue = ConvertToNewTransformSpace(transform, m_InterpEndValue, inLocalSpace);
base.OnConvertTransformSpace(transform, inLocalSpace);
}
} }
} }

View File

@@ -584,7 +584,7 @@ namespace Unity.Netcode.Components
base.OnDestroy(); base.OnDestroy();
} }
private void Awake() protected virtual void Awake()
{ {
int layers = m_Animator.layerCount; int layers = m_Animator.layerCount;
// Initializing the below arrays for everyone handles an issue // Initializing the below arrays for everyone handles an issue
@@ -952,8 +952,14 @@ namespace Unity.Netcode.Components
{ {
// Just notify all remote clients and not the local server // Just notify all remote clients and not the local server
m_ClientSendList.Clear(); m_ClientSendList.Clear();
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds); foreach (var clientId in NetworkManager.ConnectedClientsIds)
m_ClientSendList.Remove(NetworkManager.LocalClientId); {
if (clientId == NetworkManager.LocalClientId || !NetworkObject.Observers.Contains(clientId))
{
continue;
}
m_ClientSendList.Add(clientId);
}
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList; m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
SendAnimStateClientRpc(m_AnimationMessage, m_ClientRpcParams); SendAnimStateClientRpc(m_AnimationMessage, m_ClientRpcParams);
} }
@@ -1264,9 +1270,15 @@ namespace Unity.Netcode.Components
if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1)) if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1))
{ {
m_ClientSendList.Clear(); m_ClientSendList.Clear();
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds); foreach (var clientId in NetworkManager.ConnectedClientsIds)
m_ClientSendList.Remove(serverRpcParams.Receive.SenderClientId); {
m_ClientSendList.Remove(NetworkManager.ServerClientId); if (clientId == serverRpcParams.Receive.SenderClientId || clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
{
continue;
}
m_ClientSendList.Add(clientId);
}
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList; m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
m_NetworkAnimatorStateChangeHandler.SendParameterUpdate(parametersUpdate, m_ClientRpcParams); m_NetworkAnimatorStateChangeHandler.SendParameterUpdate(parametersUpdate, m_ClientRpcParams);
} }
@@ -1321,9 +1333,14 @@ namespace Unity.Netcode.Components
if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1)) if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1))
{ {
m_ClientSendList.Clear(); m_ClientSendList.Clear();
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds); foreach (var clientId in NetworkManager.ConnectedClientsIds)
m_ClientSendList.Remove(serverRpcParams.Receive.SenderClientId); {
m_ClientSendList.Remove(NetworkManager.ServerClientId); if (clientId == serverRpcParams.Receive.SenderClientId || clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
{
continue;
}
m_ClientSendList.Add(clientId);
}
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList; m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
m_NetworkAnimatorStateChangeHandler.SendAnimationUpdate(animationMessage, m_ClientRpcParams); m_NetworkAnimatorStateChangeHandler.SendAnimationUpdate(animationMessage, m_ClientRpcParams);
} }
@@ -1390,9 +1407,14 @@ namespace Unity.Netcode.Components
InternalSetTrigger(animationTriggerMessage.Hash, animationTriggerMessage.IsTriggerSet); InternalSetTrigger(animationTriggerMessage.Hash, animationTriggerMessage.IsTriggerSet);
m_ClientSendList.Clear(); m_ClientSendList.Clear();
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds); foreach (var clientId in NetworkManager.ConnectedClientsIds)
m_ClientSendList.Remove(NetworkManager.ServerClientId); {
if (clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
{
continue;
}
m_ClientSendList.Add(clientId);
}
if (IsServerAuthoritative()) if (IsServerAuthoritative())
{ {
m_NetworkAnimatorStateChangeHandler.QueueTriggerUpdateToClient(animationTriggerMessage, m_ClientRpcParams); m_NetworkAnimatorStateChangeHandler.QueueTriggerUpdateToClient(animationTriggerMessage, m_ClientRpcParams);

View File

@@ -1,4 +1,4 @@
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS || COM_UNITY_MODULES_PHYSICS2D
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using UnityEngine; using UnityEngine;
@@ -14,6 +14,12 @@ namespace Unity.Netcode.Components
/// </remarks> /// </remarks>
public abstract class NetworkRigidbodyBase : NetworkBehaviour public abstract class NetworkRigidbodyBase : NetworkBehaviour
{ {
#if UNITY_EDITOR
[HideInInspector]
[SerializeField]
internal bool NetworkRigidbodyBaseExpanded;
#endif
/// <summary> /// <summary>
/// When enabled, the associated <see cref="NetworkTransform"/> will use the Rigidbody/Rigidbody2D to apply and synchronize changes in position, rotation, and /// When enabled, the associated <see cref="NetworkTransform"/> will use the Rigidbody/Rigidbody2D to apply and synchronize changes in position, rotation, and
/// allows for the use of Rigidbody interpolation/extrapolation. /// allows for the use of Rigidbody interpolation/extrapolation.
@@ -42,8 +48,10 @@ namespace Unity.Netcode.Components
private bool m_IsRigidbody2D => RigidbodyType == RigidbodyTypes.Rigidbody2D; private bool m_IsRigidbody2D => RigidbodyType == RigidbodyTypes.Rigidbody2D;
// Used to cache the authority state of this Rigidbody during the last frame // Used to cache the authority state of this Rigidbody during the last frame
private bool m_IsAuthority; private bool m_IsAuthority;
private Rigidbody m_Rigidbody;
private Rigidbody2D m_Rigidbody2D; protected internal Rigidbody m_InternalRigidbody { get; private set; }
protected internal Rigidbody2D m_InternalRigidbody2D { get; private set; }
internal NetworkTransform NetworkTransform; internal NetworkTransform NetworkTransform;
private float m_TickFrequency; private float m_TickFrequency;
private float m_TickRate; private float m_TickRate;
@@ -87,18 +95,18 @@ namespace Unity.Netcode.Components
return; return;
} }
RigidbodyType = rigidbodyType; RigidbodyType = rigidbodyType;
m_Rigidbody2D = rigidbody2D; m_InternalRigidbody2D = rigidbody2D;
m_Rigidbody = rigidbody; m_InternalRigidbody = rigidbody;
NetworkTransform = networkTransform; NetworkTransform = networkTransform;
if (m_IsRigidbody2D && m_Rigidbody2D == null) if (m_IsRigidbody2D && m_InternalRigidbody2D == null)
{ {
m_Rigidbody2D = GetComponent<Rigidbody2D>(); m_InternalRigidbody2D = GetComponent<Rigidbody2D>();
} }
else if (m_Rigidbody == null) else if (m_InternalRigidbody == null)
{ {
m_Rigidbody = GetComponent<Rigidbody>(); m_InternalRigidbody = GetComponent<Rigidbody>();
} }
SetOriginalInterpolation(); SetOriginalInterpolation();
@@ -178,14 +186,14 @@ namespace Unity.Netcode.Components
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR #if COM_UNITY_MODULES_PHYSICS2D_LINEAR
m_Rigidbody2D.linearVelocity = linearVelocity; m_InternalRigidbody2D.linearVelocity = linearVelocity;
#else #else
m_Rigidbody2D.velocity = linearVelocity; m_InternalRigidbody2D.velocity = linearVelocity;
#endif #endif
} }
else else
{ {
m_Rigidbody.linearVelocity = linearVelocity; m_InternalRigidbody.linearVelocity = linearVelocity;
} }
} }
@@ -202,14 +210,14 @@ namespace Unity.Netcode.Components
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR #if COM_UNITY_MODULES_PHYSICS2D_LINEAR
return m_Rigidbody2D.linearVelocity; return m_InternalRigidbody2D.linearVelocity;
#else #else
return m_Rigidbody2D.velocity; return m_InternalRigidbody2D.velocity;
#endif #endif
} }
else else
{ {
return m_Rigidbody.linearVelocity; return m_InternalRigidbody.linearVelocity;
} }
} }
@@ -226,11 +234,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.angularVelocity = angularVelocity.z; m_InternalRigidbody2D.angularVelocity = angularVelocity.z;
} }
else else
{ {
m_Rigidbody.angularVelocity = angularVelocity; m_InternalRigidbody.angularVelocity = angularVelocity;
} }
} }
@@ -246,11 +254,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
return Vector3.forward * m_Rigidbody2D.angularVelocity; return Vector3.forward * m_InternalRigidbody2D.angularVelocity;
} }
else else
{ {
return m_Rigidbody.angularVelocity; return m_InternalRigidbody.angularVelocity;
} }
} }
@@ -263,11 +271,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
return m_Rigidbody2D.position; return m_InternalRigidbody2D.position;
} }
else else
{ {
return m_Rigidbody.position; return m_InternalRigidbody.position;
} }
} }
@@ -282,13 +290,13 @@ namespace Unity.Netcode.Components
{ {
var quaternion = Quaternion.identity; var quaternion = Quaternion.identity;
var angles = quaternion.eulerAngles; var angles = quaternion.eulerAngles;
angles.z = m_Rigidbody2D.rotation; angles.z = m_InternalRigidbody2D.rotation;
quaternion.eulerAngles = angles; quaternion.eulerAngles = angles;
return quaternion; return quaternion;
} }
else else
{ {
return m_Rigidbody.rotation; return m_InternalRigidbody.rotation;
} }
} }
@@ -301,11 +309,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.MovePosition(position); m_InternalRigidbody2D.MovePosition(position);
} }
else else
{ {
m_Rigidbody.MovePosition(position); m_InternalRigidbody.MovePosition(position);
} }
} }
@@ -318,11 +326,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.position = position; m_InternalRigidbody2D.position = position;
} }
else else
{ {
m_Rigidbody.position = position; m_InternalRigidbody.position = position;
} }
} }
@@ -334,13 +342,13 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.position = transform.position; m_InternalRigidbody2D.position = transform.position;
m_Rigidbody2D.rotation = transform.eulerAngles.z; m_InternalRigidbody2D.rotation = transform.eulerAngles.z;
} }
else else
{ {
m_Rigidbody.position = transform.position; m_InternalRigidbody.position = transform.position;
m_Rigidbody.rotation = transform.rotation; m_InternalRigidbody.rotation = transform.rotation;
} }
} }
@@ -358,9 +366,9 @@ namespace Unity.Netcode.Components
{ {
var quaternion = Quaternion.identity; var quaternion = Quaternion.identity;
var angles = quaternion.eulerAngles; var angles = quaternion.eulerAngles;
angles.z = m_Rigidbody2D.rotation; angles.z = m_InternalRigidbody2D.rotation;
quaternion.eulerAngles = angles; quaternion.eulerAngles = angles;
m_Rigidbody2D.MoveRotation(quaternion); m_InternalRigidbody2D.MoveRotation(quaternion);
} }
else else
{ {
@@ -375,7 +383,7 @@ namespace Unity.Netcode.Components
{ {
rotation.Normalize(); rotation.Normalize();
} }
m_Rigidbody.MoveRotation(rotation); m_InternalRigidbody.MoveRotation(rotation);
} }
} }
@@ -388,11 +396,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.rotation = rotation.eulerAngles.z; m_InternalRigidbody2D.rotation = rotation.eulerAngles.z;
} }
else else
{ {
m_Rigidbody.rotation = rotation; m_InternalRigidbody.rotation = rotation;
} }
} }
@@ -404,7 +412,7 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
switch (m_Rigidbody2D.interpolation) switch (m_InternalRigidbody2D.interpolation)
{ {
case RigidbodyInterpolation2D.None: case RigidbodyInterpolation2D.None:
{ {
@@ -425,7 +433,7 @@ namespace Unity.Netcode.Components
} }
else else
{ {
switch (m_Rigidbody.interpolation) switch (m_InternalRigidbody.interpolation)
{ {
case RigidbodyInterpolation.None: case RigidbodyInterpolation.None:
{ {
@@ -454,16 +462,16 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
if (m_Rigidbody2D.IsSleeping()) if (m_InternalRigidbody2D.IsSleeping())
{ {
m_Rigidbody2D.WakeUp(); m_InternalRigidbody2D.WakeUp();
} }
} }
else else
{ {
if (m_Rigidbody.IsSleeping()) if (m_InternalRigidbody.IsSleeping())
{ {
m_Rigidbody.WakeUp(); m_InternalRigidbody.WakeUp();
} }
} }
} }
@@ -476,11 +484,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.Sleep(); m_InternalRigidbody2D.Sleep();
} }
else else
{ {
m_Rigidbody.Sleep(); m_InternalRigidbody.Sleep();
} }
} }
@@ -489,11 +497,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
return m_Rigidbody2D.bodyType == RigidbodyType2D.Kinematic; return m_InternalRigidbody2D.bodyType == RigidbodyType2D.Kinematic;
} }
else else
{ {
return m_Rigidbody.isKinematic; return m_InternalRigidbody.isKinematic;
} }
} }
@@ -518,11 +526,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.bodyType = isKinematic ? RigidbodyType2D.Kinematic : RigidbodyType2D.Dynamic; m_InternalRigidbody2D.bodyType = isKinematic ? RigidbodyType2D.Kinematic : RigidbodyType2D.Dynamic;
} }
else else
{ {
m_Rigidbody.isKinematic = isKinematic; m_InternalRigidbody.isKinematic = isKinematic;
} }
// If we are not spawned, then exit early // If we are not spawned, then exit early
@@ -539,7 +547,7 @@ namespace Unity.Netcode.Components
if (IsKinematic()) if (IsKinematic())
{ {
// If not already set to interpolate then set the Rigidbody to interpolate // If not already set to interpolate then set the Rigidbody to interpolate
if (m_Rigidbody.interpolation == RigidbodyInterpolation.Extrapolate) if (m_InternalRigidbody.interpolation == RigidbodyInterpolation.Extrapolate)
{ {
// Sleep until the next fixed update when switching from extrapolation to interpolation // Sleep until the next fixed update when switching from extrapolation to interpolation
SleepRigidbody(); SleepRigidbody();
@@ -568,11 +576,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.None; m_InternalRigidbody2D.interpolation = RigidbodyInterpolation2D.None;
} }
else else
{ {
m_Rigidbody.interpolation = RigidbodyInterpolation.None; m_InternalRigidbody.interpolation = RigidbodyInterpolation.None;
} }
break; break;
} }
@@ -580,11 +588,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.Interpolate; m_InternalRigidbody2D.interpolation = RigidbodyInterpolation2D.Interpolate;
} }
else else
{ {
m_Rigidbody.interpolation = RigidbodyInterpolation.Interpolate; m_InternalRigidbody.interpolation = RigidbodyInterpolation.Interpolate;
} }
break; break;
} }
@@ -592,11 +600,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.Extrapolate; m_InternalRigidbody2D.interpolation = RigidbodyInterpolation2D.Extrapolate;
} }
else else
{ {
m_Rigidbody.interpolation = RigidbodyInterpolation.Extrapolate; m_InternalRigidbody.interpolation = RigidbodyInterpolation.Extrapolate;
} }
break; break;
} }
@@ -711,28 +719,28 @@ namespace Unity.Netcode.Components
private void ApplyFixedJoint2D(NetworkRigidbodyBase bodyToConnect, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true) private void ApplyFixedJoint2D(NetworkRigidbodyBase bodyToConnect, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true)
{ {
transform.position = position; transform.position = position;
m_Rigidbody2D.position = position; m_InternalRigidbody2D.position = position;
m_OriginalGravitySetting = bodyToConnect.m_Rigidbody.useGravity; m_OriginalGravitySetting = bodyToConnect.m_InternalRigidbody.useGravity;
m_FixedJoint2DUsingGravity = useGravity; m_FixedJoint2DUsingGravity = useGravity;
if (!useGravity) if (!useGravity)
{ {
m_OriginalGravityScale = m_Rigidbody2D.gravityScale; m_OriginalGravityScale = m_InternalRigidbody2D.gravityScale;
m_Rigidbody2D.gravityScale = 0.0f; m_InternalRigidbody2D.gravityScale = 0.0f;
} }
if (zeroVelocity) if (zeroVelocity)
{ {
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR #if COM_UNITY_MODULES_PHYSICS2D_LINEAR
m_Rigidbody2D.linearVelocity = Vector2.zero; m_InternalRigidbody2D.linearVelocity = Vector2.zero;
#else #else
m_Rigidbody2D.velocity = Vector2.zero; m_InternalRigidbody2D.velocity = Vector2.zero;
#endif #endif
m_Rigidbody2D.angularVelocity = 0.0f; m_InternalRigidbody2D.angularVelocity = 0.0f;
} }
FixedJoint2D = gameObject.AddComponent<FixedJoint2D>(); FixedJoint2D = gameObject.AddComponent<FixedJoint2D>();
FixedJoint2D.connectedBody = bodyToConnect.m_Rigidbody2D; FixedJoint2D.connectedBody = bodyToConnect.m_InternalRigidbody2D;
OnFixedJoint2DCreated(); OnFixedJoint2DCreated();
} }
@@ -740,16 +748,16 @@ namespace Unity.Netcode.Components
private void ApplyFixedJoint(NetworkRigidbodyBase bodyToConnectTo, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true) private void ApplyFixedJoint(NetworkRigidbodyBase bodyToConnectTo, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true)
{ {
transform.position = position; transform.position = position;
m_Rigidbody.position = position; m_InternalRigidbody.position = position;
if (zeroVelocity) if (zeroVelocity)
{ {
m_Rigidbody.linearVelocity = Vector3.zero; m_InternalRigidbody.linearVelocity = Vector3.zero;
m_Rigidbody.angularVelocity = Vector3.zero; m_InternalRigidbody.angularVelocity = Vector3.zero;
} }
m_OriginalGravitySetting = m_Rigidbody.useGravity; m_OriginalGravitySetting = m_InternalRigidbody.useGravity;
m_Rigidbody.useGravity = useGravity; m_InternalRigidbody.useGravity = useGravity;
FixedJoint = gameObject.AddComponent<FixedJoint>(); FixedJoint = gameObject.AddComponent<FixedJoint>();
FixedJoint.connectedBody = bodyToConnectTo.m_Rigidbody; FixedJoint.connectedBody = bodyToConnectTo.m_InternalRigidbody;
FixedJoint.connectedMassScale = connectedMassScale; FixedJoint.connectedMassScale = connectedMassScale;
FixedJoint.massScale = massScale; FixedJoint.massScale = massScale;
OnFixedJointCreated(); OnFixedJointCreated();
@@ -861,7 +869,7 @@ namespace Unity.Netcode.Components
if (FixedJoint != null) if (FixedJoint != null)
{ {
FixedJoint.connectedBody = null; FixedJoint.connectedBody = null;
m_Rigidbody.useGravity = m_OriginalGravitySetting; m_InternalRigidbody.useGravity = m_OriginalGravitySetting;
Destroy(FixedJoint); Destroy(FixedJoint);
FixedJoint = null; FixedJoint = null;
ResetInterpolation(); ResetInterpolation();

View File

@@ -12,6 +12,9 @@ namespace Unity.Netcode.Components
[AddComponentMenu("Netcode/Network Rigidbody")] [AddComponentMenu("Netcode/Network Rigidbody")]
public class NetworkRigidbody : NetworkRigidbodyBase public class NetworkRigidbody : NetworkRigidbodyBase
{ {
public Rigidbody Rigidbody => m_InternalRigidbody;
protected virtual void Awake() protected virtual void Awake()
{ {
Initialize(RigidbodyTypes.Rigidbody); Initialize(RigidbodyTypes.Rigidbody);

View File

@@ -12,6 +12,7 @@ namespace Unity.Netcode.Components
[AddComponentMenu("Netcode/Network Rigidbody 2D")] [AddComponentMenu("Netcode/Network Rigidbody 2D")]
public class NetworkRigidbody2D : NetworkRigidbodyBase public class NetworkRigidbody2D : NetworkRigidbodyBase
{ {
public Rigidbody2D Rigidbody2D => m_InternalRigidbody2D;
protected virtual void Awake() protected virtual void Awake()
{ {
Initialize(RigidbodyTypes.Rigidbody2D); Initialize(RigidbodyTypes.Rigidbody2D);

File diff suppressed because it is too large Load Diff

View File

@@ -735,42 +735,23 @@ namespace Unity.Netcode
RemovePendingClient(ownerClientId); RemovePendingClient(ownerClientId);
var client = AddClient(ownerClientId); var client = AddClient(ownerClientId);
if (!NetworkManager.DistributedAuthorityMode && response.CreatePlayerObject && NetworkManager.NetworkConfig.PlayerPrefab != null)
{
var prefabNetworkObject = NetworkManager.NetworkConfig.PlayerPrefab.GetComponent<NetworkObject>();
var playerPrefabHash = response.PlayerPrefabHash ?? prefabNetworkObject.GlobalObjectIdHash;
// Generate a SceneObject for the player object to spawn // Server-side spawning (only if there is a prefab hash or player prefab provided)
// Note: This is only to create the local NetworkObject, many of the serialized properties of the player prefab will be set when instantiated. if (!NetworkManager.DistributedAuthorityMode && response.CreatePlayerObject && (response.PlayerPrefabHash.HasValue || NetworkManager.NetworkConfig.PlayerPrefab != null))
var sceneObject = new NetworkObject.SceneObject
{ {
OwnerClientId = ownerClientId, var playerObject = response.PlayerPrefabHash.HasValue ? NetworkManager.SpawnManager.GetNetworkObjectToSpawn(response.PlayerPrefabHash.Value, ownerClientId, response.Position.GetValueOrDefault(), response.Rotation.GetValueOrDefault())
IsPlayerObject = true, : NetworkManager.SpawnManager.GetNetworkObjectToSpawn(NetworkManager.NetworkConfig.PlayerPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash, ownerClientId, response.Position.GetValueOrDefault(), response.Rotation.GetValueOrDefault());
IsSceneObject = false,
HasTransform = prefabNetworkObject.SynchronizeTransform,
Hash = playerPrefabHash,
TargetClientId = ownerClientId,
DontDestroyWithOwner = prefabNetworkObject.DontDestroyWithOwner,
Transform = new NetworkObject.SceneObject.TransformData
{
Position = response.Position.GetValueOrDefault(),
Rotation = response.Rotation.GetValueOrDefault()
}
};
// Create the player NetworkObject locally
var networkObject = NetworkManager.SpawnManager.CreateLocalNetworkObject(sceneObject);
// Spawn the player NetworkObject locally // Spawn the player NetworkObject locally
NetworkManager.SpawnManager.SpawnNetworkObjectLocally( NetworkManager.SpawnManager.SpawnNetworkObjectLocally(
networkObject, playerObject,
NetworkManager.SpawnManager.GetNetworkObjectId(), NetworkManager.SpawnManager.GetNetworkObjectId(),
sceneObject: false, sceneObject: false,
playerObject: true, playerObject: true,
ownerClientId, ownerClientId,
destroyWithScene: false); destroyWithScene: false);
client.AssignPlayerObject(ref networkObject); client.AssignPlayerObject(ref playerObject);
} }
// Server doesn't send itself the connection approved message // Server doesn't send itself the connection approved message
@@ -871,6 +852,7 @@ namespace Unity.Netcode
} }
} }
// Exit early if no player object was spawned
if (!response.CreatePlayerObject || (response.PlayerPrefabHash == null && NetworkManager.NetworkConfig.PlayerPrefab == null)) if (!response.CreatePlayerObject || (response.PlayerPrefabHash == null && NetworkManager.NetworkConfig.PlayerPrefab == null))
{ {
return; return;
@@ -1003,10 +985,18 @@ namespace Unity.Netcode
ConnectedClientIds.Add(clientId); ConnectedClientIds.Add(clientId);
} }
var distributedAuthority = NetworkManager.DistributedAuthorityMode;
var sessionOwnerId = NetworkManager.CurrentSessionOwner;
var isSessionOwner = NetworkManager.LocalClient.IsSessionOwner;
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList) foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
{ {
if (networkObject.SpawnWithObservers) if (networkObject.SpawnWithObservers)
{ {
// Don't add the client to the observers if hidden from the session owner
if (networkObject.IsOwner && distributedAuthority && !isSessionOwner && !networkObject.Observers.Contains(sessionOwnerId))
{
continue;
}
networkObject.Observers.Add(clientId); networkObject.Observers.Add(clientId);
} }
} }
@@ -1308,9 +1298,17 @@ namespace Unity.Netcode
internal void DisconnectClient(ulong clientId, string reason = null) internal void DisconnectClient(ulong clientId, string reason = null)
{ {
if (!LocalClient.IsServer) if (!LocalClient.IsServer)
{
if (NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.ClientServer)
{ {
throw new NotServerException($"Only server can disconnect remote clients. Please use `{nameof(Shutdown)}()` instead."); throw new NotServerException($"Only server can disconnect remote clients. Please use `{nameof(Shutdown)}()` instead.");
} }
else
{
Debug.LogWarning($"Currently, clients cannot disconnect other clients from a distributed authority session. Please use `{nameof(Shutdown)}()` instead.");
return;
}
}
if (clientId == NetworkManager.ServerClientId) if (clientId == NetworkManager.ServerClientId)
{ {

View File

@@ -19,6 +19,12 @@ namespace Unity.Netcode
/// </summary> /// </summary>
public abstract class NetworkBehaviour : MonoBehaviour public abstract class NetworkBehaviour : MonoBehaviour
{ {
#if UNITY_EDITOR
[HideInInspector]
[SerializeField]
internal bool ShowTopMostFoldoutHeaderGroup = true;
#endif
#pragma warning disable IDE1006 // disable naming rule violation check #pragma warning disable IDE1006 // disable naming rule violation check
// RuntimeAccessModifiersILPP will make this `public` // RuntimeAccessModifiersILPP will make this `public`
@@ -688,6 +694,8 @@ namespace Unity.Netcode
/// </remarks> /// </remarks>
protected virtual void OnNetworkPostSpawn() { } protected virtual void OnNetworkPostSpawn() { }
protected internal virtual void InternalOnNetworkPostSpawn() { }
/// <summary> /// <summary>
/// This method is only available client-side. /// This method is only available client-side.
/// When a new client joins it's synchronized with all spawned NetworkObjects and scenes loaded for the session joined. At the end of the synchronization process, when all /// When a new client joins it's synchronized with all spawned NetworkObjects and scenes loaded for the session joined. At the end of the synchronization process, when all
@@ -700,6 +708,8 @@ namespace Unity.Netcode
/// </remarks> /// </remarks>
protected virtual void OnNetworkSessionSynchronized() { } protected virtual void OnNetworkSessionSynchronized() { }
protected internal virtual void InternalOnNetworkSessionSynchronized() { }
/// <summary> /// <summary>
/// When a scene is loaded and in-scene placed NetworkObjects are finished spawning, this method is invoked on all of the newly spawned in-scene placed NetworkObjects. /// When a scene is loaded and in-scene placed NetworkObjects are finished spawning, this method is invoked on all of the newly spawned in-scene placed NetworkObjects.
/// This method runs both client and server side. /// This method runs both client and server side.
@@ -759,6 +769,7 @@ namespace Unity.Netcode
{ {
try try
{ {
InternalOnNetworkPostSpawn();
OnNetworkPostSpawn(); OnNetworkPostSpawn();
} }
catch (Exception e) catch (Exception e)
@@ -771,6 +782,7 @@ namespace Unity.Netcode
{ {
try try
{ {
InternalOnNetworkSessionSynchronized();
OnNetworkSessionSynchronized(); OnNetworkSessionSynchronized();
} }
catch (Exception e) catch (Exception e)
@@ -853,6 +865,8 @@ namespace Unity.Netcode
/// <param name="parentNetworkObject">the new <see cref="NetworkObject"/> parent</param> /// <param name="parentNetworkObject">the new <see cref="NetworkObject"/> parent</param>
public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { } public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
internal virtual void InternalOnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
private bool m_VarInit = false; private bool m_VarInit = false;
private readonly List<HashSet<int>> m_DeliveryMappedNetworkVariableIndices = new List<HashSet<int>>(); private readonly List<HashSet<int>> m_DeliveryMappedNetworkVariableIndices = new List<HashSet<int>>();

View File

@@ -17,6 +17,12 @@ namespace Unity.Netcode
[AddComponentMenu("Netcode/Network Manager", -100)] [AddComponentMenu("Netcode/Network Manager", -100)]
public class NetworkManager : MonoBehaviour, INetworkUpdateSystem public class NetworkManager : MonoBehaviour, INetworkUpdateSystem
{ {
#if UNITY_EDITOR
// Inspector view expand/collapse settings for this derived child class
[HideInInspector]
public bool NetworkManagerExpanded;
#endif
// TODO: Deprecate... // TODO: Deprecate...
// The following internal values are not used, but because ILPP makes them public in the assembly, they cannot // The following internal values are not used, but because ILPP makes them public in the assembly, they cannot
// be removed thanks to our semver validation. // be removed thanks to our semver validation.
@@ -189,7 +195,6 @@ namespace Unity.Netcode
OnSessionOwnerPromoted?.Invoke(sessionOwner); OnSessionOwnerPromoted?.Invoke(sessionOwner);
} }
// TODO: Make this internal after testing
internal void PromoteSessionOwner(ulong clientId) internal void PromoteSessionOwner(ulong clientId)
{ {
if (!DistributedAuthorityMode) if (!DistributedAuthorityMode)
@@ -890,6 +895,11 @@ namespace Unity.Netcode
OnNetworkManagerReset?.Invoke(this); OnNetworkManagerReset?.Invoke(this);
} }
protected virtual void OnValidateComponent()
{
}
internal void OnValidate() internal void OnValidate()
{ {
if (NetworkConfig == null) if (NetworkConfig == null)
@@ -950,6 +960,15 @@ namespace Unity.Netcode
} }
} }
} }
try
{
OnValidateComponent();
}
catch (Exception ex)
{
Debug.LogException(ex);
}
} }
private void ModeChanged(PlayModeStateChange change) private void ModeChanged(PlayModeStateChange change)

View File

@@ -67,6 +67,7 @@ namespace Unity.Netcode
/// </remarks> /// </remarks>
public List<NetworkTransform> NetworkTransforms { get; private set; } public List<NetworkTransform> NetworkTransforms { get; private set; }
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
/// <summary> /// <summary>
/// All <see cref="NetworkRigidbodyBase"></see> component instances associated with a <see cref="NetworkObject"/> component instance. /// All <see cref="NetworkRigidbodyBase"></see> component instances associated with a <see cref="NetworkObject"/> component instance.
@@ -937,6 +938,7 @@ namespace Unity.Netcode
/// <summary> /// <summary>
/// If true, the object will always be replicated as root on clients and the parent will be ignored. /// If true, the object will always be replicated as root on clients and the parent will be ignored.
/// </summary> /// </summary>
[Tooltip("If enabled (default disabled), instances of this NetworkObject will ignore any parent(s) it might have and replicate on clients as the root being its parent.")]
public bool AlwaysReplicateAsRoot; public bool AlwaysReplicateAsRoot;
/// <summary> /// <summary>
@@ -954,6 +956,8 @@ namespace Unity.Netcode
/// bandwidth cost. This can also be useful for UI elements that have /// bandwidth cost. This can also be useful for UI elements that have
/// a predetermined fixed position. /// a predetermined fixed position.
/// </remarks> /// </remarks>
[Tooltip("If enabled (default enabled), newly joining clients will be synchronized with the transform of the associated GameObject this component is attached to. Typical use case" +
" scenario would be for managment objects or in-scene placed objects that don't move and already have their transform settings applied within the scene information.")]
public bool SynchronizeTransform = true; public bool SynchronizeTransform = true;
/// <summary> /// <summary>
@@ -1011,6 +1015,7 @@ namespace Unity.Netcode
/// To synchronize clients of a <see cref="NetworkObject"/>'s scene being changed via <see cref="SceneManager.MoveGameObjectToScene(GameObject, Scene)"/>, /// To synchronize clients of a <see cref="NetworkObject"/>'s scene being changed via <see cref="SceneManager.MoveGameObjectToScene(GameObject, Scene)"/>,
/// make sure <see cref="SceneMigrationSynchronization"/> is enabled (it is by default). /// make sure <see cref="SceneMigrationSynchronization"/> is enabled (it is by default).
/// </remarks> /// </remarks>
[Tooltip("When enabled (default disabled), spawned instances of this NetworkObject will automatically migrate to any newly assigned active scene.")]
public bool ActiveSceneSynchronization; public bool ActiveSceneSynchronization;
/// <summary> /// <summary>
@@ -1029,6 +1034,7 @@ namespace Unity.Netcode
/// is <see cref="true"/> and <see cref="ActiveSceneSynchronization"/> is <see cref="false"/> and the scene is not the currently /// is <see cref="true"/> and <see cref="ActiveSceneSynchronization"/> is <see cref="false"/> and the scene is not the currently
/// active scene, then the <see cref="NetworkObject"/> will be destroyed. /// active scene, then the <see cref="NetworkObject"/> will be destroyed.
/// </remarks> /// </remarks>
[Tooltip("When enabled (default enabled), dynamically spawned instances of this NetworkObject's migration to a different scene will automatically be synchonize amongst clients.")]
public bool SceneMigrationSynchronization = true; public bool SceneMigrationSynchronization = true;
/// <summary> /// <summary>
@@ -1044,7 +1050,7 @@ namespace Unity.Netcode
/// <summary> /// <summary>
/// When set to false, the NetworkObject will be spawned with no observers initially (other than the server) /// When set to false, the NetworkObject will be spawned with no observers initially (other than the server)
/// </summary> /// </summary>
[Tooltip("When false, the NetworkObject will spawn with no observers initially. (default is true)")] [Tooltip("When disabled (default enabled), the NetworkObject will spawn with no observers. You control object visibility using NetworkShow. This applies to newly joining clients as well.")]
public bool SpawnWithObservers = true; public bool SpawnWithObservers = true;
/// <summary> /// <summary>
@@ -1073,13 +1079,35 @@ namespace Unity.Netcode
/// Whether or not to destroy this object if it's owner is destroyed. /// Whether or not to destroy this object if it's owner is destroyed.
/// If true, the objects ownership will be given to the server. /// If true, the objects ownership will be given to the server.
/// </summary> /// </summary>
[Tooltip("When enabled (default disabled), instances of this NetworkObject will not be destroyed if the owning client disconnects.")]
public bool DontDestroyWithOwner; public bool DontDestroyWithOwner;
/// <summary> /// <summary>
/// Whether or not to enable automatic NetworkObject parent synchronization. /// Whether or not to enable automatic NetworkObject parent synchronization.
/// </summary> /// </summary>
[Tooltip("When disabled (default enabled), NetworkObject parenting will not be automatically synchronized. This is typically used when you want to implement your own custom parenting solution.")]
public bool AutoObjectParentSync = true; public bool AutoObjectParentSync = true;
/// <summary>
/// Determines if the owner will apply transform values sent by the parenting message.
/// </summary>
/// <remarks>
/// When enabled, the resultant parenting transform changes sent by the authority will be applied on all instances. <br />
/// When disabled, the resultant parenting transform changes sent by the authority will not be applied on the owner's instance. <br />
/// When disabled, all non-owner instances will still be synchronized by the authority's transform values when parented.
/// When using a <see cref="NetworkTopologyTypes.ClientServer"/> network topology and an owner authoritative motion model, disabling this can help smooth parenting transitions.
/// When using a <see cref="NetworkTopologyTypes.DistributedAuthority"/> network topology this will have no impact on the owner's instance since only the authority/owner can parent.
/// </remarks>
[Tooltip("When disabled (default enabled), the owner will not apply a server or host's transform properties when parenting changes. Primarily useful for client-server network topology configurations.")]
public bool SyncOwnerTransformWhenParented = true;
/// <summary>
/// Client-Server specific, when enabled an owner of a NetworkObject can parent locally as opposed to requiring the owner to notify the server it would like to be parented.
/// This behavior is always true when using a distributed authority network topology and does not require it to be set.
/// </summary>
[Tooltip("When enabled (default disabled), owner's can parent a NetworkObject locally without having to send an RPC to the server or host. Only pertinent when using client-server network topology configurations.")]
public bool AllowOwnerToParent;
internal readonly HashSet<ulong> Observers = new HashSet<ulong>(); internal readonly HashSet<ulong> Observers = new HashSet<ulong>();
#if MULTIPLAYER_TOOLS #if MULTIPLAYER_TOOLS
@@ -1787,6 +1815,9 @@ namespace Unity.Netcode
{ {
for (int i = 0; i < ChildNetworkBehaviours.Count; i++) for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
{ {
// Invoke internal notification
ChildNetworkBehaviours[i].InternalOnNetworkObjectParentChanged(parentNetworkObject);
// Invoke public notification
ChildNetworkBehaviours[i].OnNetworkObjectParentChanged(parentNetworkObject); ChildNetworkBehaviours[i].OnNetworkObjectParentChanged(parentNetworkObject);
} }
} }
@@ -1918,7 +1949,7 @@ namespace Unity.Netcode
// DANGO-TODO: Do we want to worry about ownership permissions here? // DANGO-TODO: Do we want to worry about ownership permissions here?
// It wouldn't make sense to not allow parenting, but keeping this note here as a reminder. // It wouldn't make sense to not allow parenting, but keeping this note here as a reminder.
var isAuthority = HasAuthority; var isAuthority = HasAuthority || (AllowOwnerToParent && IsOwner);
// If we don't have authority and we are not shutting down, then don't allow any parenting. // If we don't have authority and we are not shutting down, then don't allow any parenting.
// If we are shutting down and don't have authority then allow it. // If we are shutting down and don't have authority then allow it.
@@ -1984,7 +2015,7 @@ namespace Unity.Netcode
var isAuthority = false; var isAuthority = false;
// With distributed authority, we need to track "valid authoritative" parenting changes. // With distributed authority, we need to track "valid authoritative" parenting changes.
// So, either the authority or AuthorityAppliedParenting is considered a "valid parenting change". // So, either the authority or AuthorityAppliedParenting is considered a "valid parenting change".
isAuthority = HasAuthority || AuthorityAppliedParenting; isAuthority = HasAuthority || AuthorityAppliedParenting || (AllowOwnerToParent && IsOwner);
var distributedAuthority = NetworkManager.DistributedAuthorityMode; var distributedAuthority = NetworkManager.DistributedAuthorityMode;
// If we do not have authority and we are spawned // If we do not have authority and we are spawned
@@ -2076,7 +2107,7 @@ namespace Unity.Netcode
} }
// If we are connected to a CMB service or we are running a mock CMB service then send to the "server" identifier // If we are connected to a CMB service or we are running a mock CMB service then send to the "server" identifier
if (distributedAuthority) if (distributedAuthority || (!distributedAuthority && AllowOwnerToParent && IsOwner && !NetworkManager.IsServer))
{ {
if (!NetworkManager.DAHost) if (!NetworkManager.DAHost)
{ {
@@ -2365,7 +2396,9 @@ namespace Unity.Netcode
{ {
NetworkTransforms = new List<NetworkTransform>(); NetworkTransforms = new List<NetworkTransform>();
} }
NetworkTransforms.Add(networkBehaviours[i] as NetworkTransform); var networkTransform = networkBehaviours[i] as NetworkTransform;
networkTransform.IsNested = i != 0 && networkTransform.gameObject != gameObject;
NetworkTransforms.Add(networkTransform);
} }
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
else if (type.IsSubclassOf(typeof(NetworkRigidbodyBase))) else if (type.IsSubclassOf(typeof(NetworkRigidbodyBase)))

View File

@@ -95,6 +95,7 @@ namespace Unity.Netcode
return; return;
} }
ValidateMessageSize(messageBuffer, networkDelivery, isNamed: false);
if (m_NetworkManager.IsHost) if (m_NetworkManager.IsHost)
{ {
@@ -131,6 +132,8 @@ namespace Unity.Netcode
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param> /// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
public void SendUnnamedMessage(ulong clientId, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) public void SendUnnamedMessage(ulong clientId, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
{ {
ValidateMessageSize(messageBuffer, networkDelivery, isNamed: false);
if (m_NetworkManager.IsHost) if (m_NetworkManager.IsHost)
{ {
if (clientId == m_NetworkManager.LocalClientId) if (clientId == m_NetworkManager.LocalClientId)
@@ -286,6 +289,8 @@ namespace Unity.Netcode
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param> /// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
public void SendNamedMessage(string messageName, ulong clientId, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) public void SendNamedMessage(string messageName, ulong clientId, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
{ {
ValidateMessageSize(messageStream, networkDelivery, isNamed: true);
ulong hash = 0; ulong hash = 0;
switch (m_NetworkManager.NetworkConfig.RpcHashSize) switch (m_NetworkManager.NetworkConfig.RpcHashSize)
{ {
@@ -367,6 +372,8 @@ namespace Unity.Netcode
return; return;
} }
ValidateMessageSize(messageStream, networkDelivery, isNamed: true);
ulong hash = 0; ulong hash = 0;
switch (m_NetworkManager.NetworkConfig.RpcHashSize) switch (m_NetworkManager.NetworkConfig.RpcHashSize)
{ {
@@ -405,5 +412,32 @@ namespace Unity.Netcode
m_NetworkManager.NetworkMetrics.TrackNamedMessageSent(clientIds, messageName, size); m_NetworkManager.NetworkMetrics.TrackNamedMessageSent(clientIds, messageName, size);
} }
} }
/// <summary>
/// Validate the size of the message. If it's a non-fragmented delivery type the message must fit within the
/// max allowed size with headers also subtracted. Named messages also include the hash
/// of the name string. Only validates in editor and development builds.
/// </summary>
/// <param name="messageStream">The named message payload</param>
/// <param name="networkDelivery">Delivery method</param>
/// <param name="isNamed">Is the message named (or unnamed)</param>
/// <exception cref="OverflowException">Exception thrown in case validation fails</exception>
private unsafe void ValidateMessageSize(FastBufferWriter messageStream, NetworkDelivery networkDelivery, bool isNamed)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
var maxNonFragmentedSize = m_NetworkManager.MessageManager.NonFragmentedMessageMaxSize - FastBufferWriter.GetWriteSize<NetworkMessageHeader>() - sizeof(NetworkBatchHeader);
if (isNamed)
{
maxNonFragmentedSize -= sizeof(ulong); // MessageName hash
}
if (networkDelivery != NetworkDelivery.ReliableFragmentedSequenced
&& messageStream.Length > maxNonFragmentedSize)
{
throw new OverflowException($"Given message size ({messageStream.Length} bytes) is greater than " +
$"the maximum allowed for the selected delivery method ({maxNonFragmentedSize} bytes). Try using " +
$"ReliableFragmentedSequenced delivery method instead.");
}
#endif
}
} }
} }

View File

@@ -55,6 +55,15 @@ namespace Unity.Netcode
// Don't redistribute for the local instance // Don't redistribute for the local instance
if (ClientId != networkManager.LocalClientId) if (ClientId != networkManager.LocalClientId)
{ {
// Show any NetworkObjects that are:
// - Hidden from the session owner
// - Owned by this client
// - Has NetworkObject.SpawnWithObservers set to true (the default)
if (!networkManager.LocalClient.IsSessionOwner)
{
networkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(ClientId);
}
// We defer redistribution to the end of the NetworkUpdateStage.PostLateUpdate // We defer redistribution to the end of the NetworkUpdateStage.PostLateUpdate
networkManager.RedistributeToClient = true; networkManager.RedistributeToClient = true;
networkManager.ClientToRedistribute = ClientId; networkManager.ClientToRedistribute = ClientId;

View File

@@ -117,6 +117,11 @@ namespace Unity.Netcode
networkObject.SetNetworkParenting(LatestParent, WorldPositionStays); networkObject.SetNetworkParenting(LatestParent, WorldPositionStays);
networkObject.ApplyNetworkParenting(RemoveParent); networkObject.ApplyNetworkParenting(RemoveParent);
// This check is primarily for client-server network topologies when the motion model is owner authoritative:
// When SyncOwnerTransformWhenParented is enabled, then always apply the transform values.
// When SyncOwnerTransformWhenParented is disabled, then only synchronize the transform on non-owner instances.
if (networkObject.SyncOwnerTransformWhenParented || (!networkObject.SyncOwnerTransformWhenParented && !networkObject.IsOwner))
{
// We set all of the transform values after parenting as they are // We set all of the transform values after parenting as they are
// the values of the server-side post-parenting transform values // the values of the server-side post-parenting transform values
if (!WorldPositionStays) if (!WorldPositionStays)
@@ -130,9 +135,10 @@ namespace Unity.Netcode
networkObject.transform.rotation = Rotation; networkObject.transform.rotation = Rotation;
} }
networkObject.transform.localScale = Scale; networkObject.transform.localScale = Scale;
}
// If in distributed authority mode and we are running a DAHost and this is the DAHost, then forward the parent changed message to any remaining clients // If in distributed authority mode and we are running a DAHost and this is the DAHost, then forward the parent changed message to any remaining clients
if (networkManager.DistributedAuthorityMode && !networkManager.CMBServiceConnection && networkManager.DAHost) if ((networkManager.DistributedAuthorityMode && !networkManager.CMBServiceConnection && networkManager.DAHost) || (networkObject.AllowOwnerToParent && context.SenderId == networkObject.OwnerClientId && networkManager.IsServer))
{ {
var size = 0; var size = 0;
var message = this; var message = this;

View File

@@ -1,4 +1,3 @@
using System;
using Unity.Collections; using Unity.Collections;
namespace Unity.Netcode namespace Unity.Netcode
@@ -34,22 +33,14 @@ namespace Unity.Netcode
var networkManager = (NetworkManager)context.SystemOwner; var networkManager = (NetworkManager)context.SystemOwner;
if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(WrappedMessage.Metadata.NetworkObjectId, out var networkObject)) if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(WrappedMessage.Metadata.NetworkObjectId, out var networkObject))
{ {
// With distributed authority mode, we can send Rpcs before we have been notified the NetworkObject is despawned. // If the NetworkObject no longer exists then just log a warning when developer mode logging is enabled and exit.
// DANGO-TODO: Should the CMB Service cull out any Rpcs targeting recently despawned NetworkObjects? // This can happen if NetworkObject is despawned and a client sends an RPC before receiving the despawn message.
// DANGO-TODO: This would require the service to keep track of despawned NetworkObjects since we re-use NetworkObject identifiers.
if (networkManager.DistributedAuthorityMode)
{
if (networkManager.LogLevel == LogLevel.Developer) if (networkManager.LogLevel == LogLevel.Developer)
{ {
NetworkLog.LogWarning($"[{WrappedMessage.Metadata.NetworkObjectId}, {WrappedMessage.Metadata.NetworkBehaviourId}, {WrappedMessage.Metadata.NetworkRpcMethodId}]An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs."); NetworkLog.LogWarning($"[{WrappedMessage.Metadata.NetworkObjectId}, {WrappedMessage.Metadata.NetworkBehaviourId}, {WrappedMessage.Metadata.NetworkRpcMethodId}] An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
} }
return; return;
} }
else
{
throw new InvalidOperationException($"[{WrappedMessage.Metadata.NetworkObjectId}, {WrappedMessage.Metadata.NetworkBehaviourId}, {WrappedMessage.Metadata.NetworkRpcMethodId}]An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
}
}
var observers = networkObject.Observers; var observers = networkObject.Observers;

View File

@@ -60,7 +60,13 @@ namespace Unity.Netcode
var networkManager = (NetworkManager)context.SystemOwner; var networkManager = (NetworkManager)context.SystemOwner;
if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(metadata.NetworkObjectId, out var networkObject)) if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(metadata.NetworkObjectId, out var networkObject))
{ {
throw new InvalidOperationException($"An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs."); // If the NetworkObject no longer exists then just log a warning when developer mode logging is enabled and exit.
// This can happen if NetworkObject is despawned and a client sends an RPC before receiving the despawn message.
if (networkManager.LogLevel == LogLevel.Developer)
{
NetworkLog.LogWarning($"[{metadata.NetworkObjectId}, {metadata.NetworkBehaviourId}, {metadata.NetworkRpcMethodId}] An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
}
return;
} }
var networkBehaviour = networkObject.GetNetworkBehaviourAtOrderIndex(metadata.NetworkBehaviourId); var networkBehaviour = networkObject.GetNetworkBehaviourAtOrderIndex(metadata.NetworkBehaviourId);

View File

@@ -20,7 +20,7 @@ namespace Unity.Netcode
public void Handle(ref NetworkContext context) public void Handle(ref NetworkContext context)
{ {
((NetworkManager)context.SystemOwner).CustomMessagingManager.InvokeUnnamedMessage(context.SenderId, m_ReceivedData, context.SerializedHeaderSize); ((NetworkManager)context.SystemOwner).CustomMessagingManager?.InvokeUnnamedMessage(context.SenderId, m_ReceivedData, context.SerializedHeaderSize);
} }
} }
} }

View File

@@ -733,7 +733,11 @@ namespace Unity.Netcode
} }
ref var writeQueueItem = ref sendQueueItem.ElementAt(sendQueueItem.Length - 1); ref var writeQueueItem = ref sendQueueItem.ElementAt(sendQueueItem.Length - 1);
writeQueueItem.Writer.TryBeginWrite(tmpSerializer.Length + headerSerializer.Length); if (!writeQueueItem.Writer.TryBeginWrite(tmpSerializer.Length + headerSerializer.Length))
{
Debug.LogError($"Not enough space to write message, size={tmpSerializer.Length + headerSerializer.Length} space used={writeQueueItem.Writer.Position} total size={writeQueueItem.Writer.Capacity}");
continue;
}
writeQueueItem.Writer.WriteBytes(headerSerializer.GetUnsafePtr(), headerSerializer.Length); writeQueueItem.Writer.WriteBytes(headerSerializer.GetUnsafePtr(), headerSerializer.Length);
writeQueueItem.Writer.WriteBytes(tmpSerializer.GetUnsafePtr(), tmpSerializer.Length); writeQueueItem.Writer.WriteBytes(tmpSerializer.GetUnsafePtr(), tmpSerializer.Length);

View File

@@ -187,7 +187,9 @@ namespace Unity.Netcode
internal bool CanSend() internal bool CanSend()
{ {
var timeSinceLastUpdate = m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime - LastUpdateSent; // When connected to a service or not the server, always use the synchronized server time as opposed to the local time
var time = m_InternalNetworkManager.CMBServiceConnection || !m_InternalNetworkManager.IsServer ? m_NetworkBehaviour.NetworkManager.ServerTime.Time : m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime;
var timeSinceLastUpdate = time - LastUpdateSent;
return return
( (
UpdateTraits.MaxSecondsBetweenUpdates > 0 && UpdateTraits.MaxSecondsBetweenUpdates > 0 &&
@@ -201,7 +203,8 @@ namespace Unity.Netcode
internal void UpdateLastSentTime() internal void UpdateLastSentTime()
{ {
LastUpdateSent = m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime; // When connected to a service or not the server, always use the synchronized server time as opposed to the local time
LastUpdateSent = m_InternalNetworkManager.CMBServiceConnection || !m_InternalNetworkManager.IsServer ? m_NetworkBehaviour.NetworkManager.ServerTime.Time : m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime;
} }
internal static bool IgnoreInitializeWarning; internal static bool IgnoreInitializeWarning;

View File

@@ -2550,17 +2550,6 @@ namespace Unity.Netcode
// At this point the client is considered fully "connected" // At this point the client is considered fully "connected"
if ((NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClient.IsSessionOwner) || !NetworkManager.DistributedAuthorityMode) if ((NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClient.IsSessionOwner) || !NetworkManager.DistributedAuthorityMode)
{ {
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost)
{
// DANGO-EXP TODO: Remove this once service is sending the synchronization message to all clients
if (NetworkManager.ConnectedClients.ContainsKey(clientId) && NetworkManager.ConnectionManager.ConnectedClientIds.Contains(clientId) && NetworkManager.ConnectedClientsList.Contains(NetworkManager.ConnectedClients[clientId]))
{
EndSceneEvent(sceneEventId);
return;
}
NetworkManager.ConnectionManager.AddClient(clientId);
}
// Notify the local server that a client has finished synchronizing // Notify the local server that a client has finished synchronizing
OnSceneEvent?.Invoke(new SceneEvent() OnSceneEvent?.Invoke(new SceneEvent()
{ {
@@ -2575,6 +2564,20 @@ namespace Unity.Netcode
} }
else else
{ {
// Notify the local server that a client has finished synchronizing
OnSceneEvent?.Invoke(new SceneEvent()
{
SceneEventType = sceneEventData.SceneEventType,
SceneName = string.Empty,
ClientId = clientId
});
// Show any NetworkObjects that are:
// - Hidden from the session owner
// - Owned by this client
// - Has NetworkObject.SpawnWithObservers set to true (the default)
NetworkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(clientId);
// DANGO-EXP TODO: Remove this once service distributes objects // DANGO-EXP TODO: Remove this once service distributes objects
// Non-session owners receive this notification from newly connected clients and upon receiving // Non-session owners receive this notification from newly connected clients and upon receiving
// the event they will redistribute their NetworkObjects // the event they will redistribute their NetworkObjects
@@ -2589,9 +2592,6 @@ namespace Unity.Netcode
// At this time the client is fully synchronized with all loaded scenes and // At this time the client is fully synchronized with all loaded scenes and
// NetworkObjects and should be considered "fully connected". Send the // NetworkObjects and should be considered "fully connected". Send the
// notification that the client is connected. // notification that the client is connected.
// TODO 2023: We should have a better name for this or have multiple states the
// client progresses through (the name and associated legacy behavior/expected state
// of the client was persisted since MLAPI)
NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(clientId); NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(clientId);
if (NetworkManager.IsHost) if (NetworkManager.IsHost)
@@ -2664,9 +2664,14 @@ namespace Unity.Netcode
EventData = sceneEventData, EventData = sceneEventData,
}; };
// Forward synchronization to client then exit early because DAHost is not the current session owner // Forward synchronization to client then exit early because DAHost is not the current session owner
NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, NetworkManager.CurrentSessionOwner); foreach (var client in NetworkManager.ConnectedClientsIds)
EndSceneEvent(sceneEventData.SceneEventId); {
return; if (client == NetworkManager.LocalClientId)
{
continue;
}
NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, client);
}
} }
} }
else else

View File

@@ -700,7 +700,7 @@ namespace Unity.Netcode
} }
if (Handle->Position + size > Handle->AllowedWriteMark) if (Handle->Position + size > Handle->AllowedWriteMark)
{ {
throw new OverflowException($"Attempted to write without first calling {nameof(TryBeginWrite)}()"); throw new OverflowException($"Attempted to write without first calling {nameof(TryBeginWrite)}(), Position+Size={Handle->Position + size} > AllowedWriteMark={Handle->AllowedWriteMark}");
} }
#endif #endif
UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size); UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size);
@@ -729,7 +729,7 @@ namespace Unity.Netcode
if (!TryBeginWriteInternal(size)) if (!TryBeginWriteInternal(size))
{ {
throw new OverflowException("Writing past the end of the buffer"); throw new OverflowException($"Writing past the end of the buffer, size is {size} bytes but remaining capacity is {Handle->Capacity - Handle->Position} bytes");
} }
UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size); UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size);
Handle->Position += size; Handle->Position += size;

View File

@@ -1580,22 +1580,48 @@ namespace Unity.Netcode
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost) if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost)
{ {
foreach (var entry in ClientsToShowObject) foreach (var entry in ClientsToShowObject)
{
if (entry.Key != null && entry.Key.IsSpawned)
{
try
{ {
SendSpawnCallForObserverUpdate(entry.Value.ToArray(), entry.Key); SendSpawnCallForObserverUpdate(entry.Value.ToArray(), entry.Key);
} }
catch (Exception ex)
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
Debug.LogException(ex);
}
}
}
}
ClientsToShowObject.Clear(); ClientsToShowObject.Clear();
ObjectsToShowToClient.Clear(); ObjectsToShowToClient.Clear();
return; return;
} }
// Handle NetworkObjects to show // Server or Host handling of NetworkObjects to show
foreach (var client in ObjectsToShowToClient) foreach (var client in ObjectsToShowToClient)
{ {
ulong clientId = client.Key; ulong clientId = client.Key;
foreach (var networkObject in client.Value) foreach (var networkObject in client.Value)
{
if (networkObject != null && networkObject.IsSpawned)
{
try
{ {
SendSpawnCallForObject(clientId, networkObject); SendSpawnCallForObject(clientId, networkObject);
} }
catch (Exception ex)
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
Debug.LogException(ex);
}
}
}
}
} }
ObjectsToShowToClient.Clear(); ObjectsToShowToClient.Clear();
} }
@@ -1883,5 +1909,55 @@ namespace Unity.Netcode
networkObject.InternalNetworkSessionSynchronized(); networkObject.InternalNetworkSessionSynchronized();
} }
} }
/// <summary>
/// Distributed Authority Only
/// Should be invoked on non-session owner clients when a newly joined client is finished
/// synchronizing in order to "show" (spawn) anything that might be currently hidden from
/// the session owner.
/// </summary>
internal void ShowHiddenObjectsToNewlyJoinedClient(ulong newClientId)
{
if (!NetworkManager.DistributedAuthorityMode)
{
if (NetworkManager == null || !NetworkManager.ShutdownInProgress && NetworkManager.LogLevel <= LogLevel.Developer)
{
Debug.LogWarning($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} invoked while !");
}
return;
}
if (!NetworkManager.DistributedAuthorityMode)
{
Debug.LogError($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} should only be invoked when using a distributed authority network topology!");
return;
}
if (NetworkManager.LocalClient.IsSessionOwner)
{
Debug.LogError($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} should only be invoked on a non-session owner client!");
return;
}
var localClientId = NetworkManager.LocalClient.ClientId;
var sessionOwnerId = NetworkManager.CurrentSessionOwner;
foreach (var networkObject in SpawnedObjectsList)
{
if (networkObject.SpawnWithObservers && networkObject.OwnerClientId == localClientId && !networkObject.Observers.Contains(sessionOwnerId))
{
if (networkObject.Observers.Contains(newClientId))
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
// Track if there is some other location where the client is being added to the observers list when the object is hidden from the session owner
Debug.LogWarning($"[{networkObject.name}] Has new client as an observer but it is hidden from the session owner!");
}
// For now, remove the client (impossible for the new client to have an instance since the session owner doesn't) to make sure newly added
// code to handle this edge case works.
networkObject.Observers.Remove(newClientId);
}
networkObject.NetworkShow(newClientId);
}
}
}
} }
} }

View File

@@ -850,6 +850,12 @@ namespace Unity.Netcode.TestHelpers.Runtime
protected virtual bool LogAllMessages => false; protected virtual bool LogAllMessages => false;
protected virtual bool ShouldCheckForSpawnedPlayers()
{
return true;
}
/// <summary> /// <summary>
/// This starts the server and clients as long as <see cref="CanStartServerAndClients"/> /// This starts the server and clients as long as <see cref="CanStartServerAndClients"/>
/// returns true. /// returns true.
@@ -938,7 +944,12 @@ namespace Unity.Netcode.TestHelpers.Runtime
AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{m_ServerNetworkManager.LocalClientId}'s player object!\n {m_InternalErrorLog}"); AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{m_ServerNetworkManager.LocalClientId}'s player object!\n {m_InternalErrorLog}");
} }
} }
if (ShouldCheckForSpawnedPlayers())
{
ClientNetworkManagerPostStartInit(); ClientNetworkManagerPostStartInit();
}
// Notification that at this time the server and client(s) are instantiated, // Notification that at this time the server and client(s) are instantiated,
// started, and connected on both sides. // started, and connected on both sides.
yield return OnServerAndClientsConnected(); yield return OnServerAndClientsConnected();
@@ -1030,7 +1041,10 @@ namespace Unity.Netcode.TestHelpers.Runtime
} }
} }
if (ShouldCheckForSpawnedPlayers())
{
ClientNetworkManagerPostStartInit(); ClientNetworkManagerPostStartInit();
}
// Notification that at this time the server and client(s) are instantiated, // Notification that at this time the server and client(s) are instantiated,
// started, and connected on both sides. // started, and connected on both sides.

View File

@@ -326,21 +326,31 @@ namespace Unity.Netcode.TestHelpers.Runtime
s_IsStarted = false; s_IsStarted = false;
try
{
// Shutdown the server which forces clients to disconnect // Shutdown the server which forces clients to disconnect
foreach (var networkManager in NetworkManagerInstances) foreach (var networkManager in NetworkManagerInstances)
{ {
networkManager.Shutdown(); if (networkManager != null && networkManager.IsListening)
{
networkManager?.Shutdown();
s_Hooks.Remove(networkManager); s_Hooks.Remove(networkManager);
} }
}
// Destroy the network manager instances // Destroy the network manager instances
foreach (var networkManager in NetworkManagerInstances) foreach (var networkManager in NetworkManagerInstances)
{ {
if (networkManager.gameObject != null) if (networkManager != null && networkManager.gameObject)
{ {
Object.DestroyImmediate(networkManager.gameObject); Object.DestroyImmediate(networkManager.gameObject);
} }
} }
}
catch (Exception ex)
{
Debug.LogException(ex);
}
NetworkManagerInstances.Clear(); NetworkManagerInstances.Clear();

View File

@@ -1,65 +1,135 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic;
using System.Text; using System.Text;
using NUnit.Framework; using NUnit.Framework;
using Unity.Netcode.TestHelpers.Runtime; using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using UnityEngine.TestTools; using UnityEngine.TestTools;
namespace Unity.Netcode.RuntimeTests namespace Unity.Netcode.RuntimeTests
{ {
internal class ConnectionApprovalTests [TestFixture(PlayerCreation.Prefab)]
[TestFixture(PlayerCreation.PrefabHash)]
[TestFixture(PlayerCreation.NoPlayer)]
[TestFixture(PlayerCreation.FailValidation)]
internal class ConnectionApprovalTests : NetcodeIntegrationTest
{ {
private Guid m_ValidationToken; private const string k_InvalidToken = "Invalid validation token!";
private bool m_IsValidated; public enum PlayerCreation
{
Prefab,
PrefabHash,
NoPlayer,
FailValidation
}
private PlayerCreation m_PlayerCreation;
private bool m_ClientDisconnectReasonValidated;
[SetUp] private Dictionary<ulong, bool> m_Validated = new Dictionary<ulong, bool>();
public void Setup()
public ConnectionApprovalTests(PlayerCreation playerCreation)
{ {
// Create, instantiate, and host m_PlayerCreation = playerCreation;
Assert.IsTrue(NetworkManagerHelper.StartNetworkManager(out _, NetworkManagerHelper.NetworkManagerOperatingMode.None)); }
protected override int NumberOfClients => 1;
private Guid m_ValidationToken;
protected override bool ShouldCheckForSpawnedPlayers()
{
return m_PlayerCreation != PlayerCreation.NoPlayer;
}
protected override void OnServerAndClientsCreated()
{
m_ClientDisconnectReasonValidated = false;
m_BypassConnectionTimeout = m_PlayerCreation == PlayerCreation.FailValidation;
m_Validated.Clear();
m_ValidationToken = Guid.NewGuid(); m_ValidationToken = Guid.NewGuid();
var validationToken = Encoding.UTF8.GetBytes(m_ValidationToken.ToString());
m_ServerNetworkManager.ConnectionApprovalCallback = NetworkManagerObject_ConnectionApprovalCallback;
m_ServerNetworkManager.NetworkConfig.PlayerPrefab = m_PlayerCreation == PlayerCreation.Prefab ? m_PlayerPrefab : null;
if (m_PlayerCreation == PlayerCreation.PrefabHash)
{
m_ServerNetworkManager.NetworkConfig.Prefabs.Add(new NetworkPrefab() { Prefab = m_PlayerPrefab });
}
m_ServerNetworkManager.NetworkConfig.ConnectionApproval = true;
m_ServerNetworkManager.NetworkConfig.ConnectionData = validationToken;
foreach (var client in m_ClientNetworkManagers)
{
client.NetworkConfig.PlayerPrefab = m_PlayerCreation == PlayerCreation.Prefab ? m_PlayerPrefab : null;
if (m_PlayerCreation == PlayerCreation.PrefabHash)
{
client.NetworkConfig.Prefabs.Add(new NetworkPrefab() { Prefab = m_PlayerPrefab });
}
client.NetworkConfig.ConnectionApproval = true;
client.NetworkConfig.ConnectionData = m_PlayerCreation == PlayerCreation.FailValidation ? Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()) : validationToken;
if (m_PlayerCreation == PlayerCreation.FailValidation)
{
client.OnClientDisconnectCallback += Client_OnClientDisconnectCallback;
}
}
base.OnServerAndClientsCreated();
}
private void Client_OnClientDisconnectCallback(ulong clientId)
{
m_ClientNetworkManagers[0].OnClientDisconnectCallback -= Client_OnClientDisconnectCallback;
m_ClientDisconnectReasonValidated = m_ClientNetworkManagers[0].LocalClientId == clientId && m_ClientNetworkManagers[0].DisconnectReason == k_InvalidToken;
}
private bool ClientAndHostValidated()
{
if (!m_Validated.ContainsKey(m_ServerNetworkManager.LocalClientId) || !m_Validated[m_ServerNetworkManager.LocalClientId])
{
return false;
}
if (m_PlayerCreation == PlayerCreation.FailValidation)
{
return m_ClientDisconnectReasonValidated;
}
else
{
foreach (var client in m_ClientNetworkManagers)
{
if (!m_Validated.ContainsKey(client.LocalClientId) || !m_Validated[client.LocalClientId])
{
return false;
}
}
}
return true;
} }
[UnityTest] [UnityTest]
public IEnumerator ConnectionApproval() public IEnumerator ConnectionApproval()
{ {
NetworkManagerHelper.NetworkManagerObject.ConnectionApprovalCallback = NetworkManagerObject_ConnectionApprovalCallback; yield return WaitForConditionOrTimeOut(ClientAndHostValidated);
NetworkManagerHelper.NetworkManagerObject.NetworkConfig.ConnectionApproval = true; AssertOnTimeout("Timed out waiting for all clients to be approved!");
NetworkManagerHelper.NetworkManagerObject.NetworkConfig.PlayerPrefab = null;
NetworkManagerHelper.NetworkManagerObject.NetworkConfig.ConnectionData = Encoding.UTF8.GetBytes(m_ValidationToken.ToString());
m_IsValidated = false;
NetworkManagerHelper.NetworkManagerObject.StartHost();
var timeOut = Time.realtimeSinceStartup + 3.0f;
var timedOut = false;
while (!m_IsValidated)
{
yield return new WaitForSeconds(0.01f);
if (timeOut < Time.realtimeSinceStartup)
{
timedOut = true;
}
}
//Make sure we didn't time out
Assert.False(timedOut);
Assert.True(m_IsValidated);
} }
private void NetworkManagerObject_ConnectionApprovalCallback(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response) private void NetworkManagerObject_ConnectionApprovalCallback(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
{ {
var stringGuid = Encoding.UTF8.GetString(request.Payload); var stringGuid = Encoding.UTF8.GetString(request.Payload);
if (m_ValidationToken.ToString() == stringGuid) if (m_ValidationToken.ToString() == stringGuid)
{ {
m_IsValidated = true; m_Validated.Add(request.ClientNetworkId, true);
response.Approved = true;
}
else
{
response.Approved = false;
response.Reason = "Invalid validation token!";
} }
response.Approved = m_IsValidated; response.CreatePlayerObject = ShouldCheckForSpawnedPlayers();
response.CreatePlayerObject = false;
response.Position = null; response.Position = null;
response.Rotation = null; response.Rotation = null;
response.PlayerPrefabHash = null; response.PlayerPrefabHash = m_PlayerCreation == PlayerCreation.PrefabHash ? m_PlayerPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash : null;
} }
@@ -78,13 +148,6 @@ namespace Unity.Netcode.RuntimeTests
Assert.True(currentHash != newHash, $"Hashed {nameof(NetworkConfig)} values {currentHash} and {newHash} should not be the same!"); Assert.True(currentHash != newHash, $"Hashed {nameof(NetworkConfig)} values {currentHash} and {newHash} should not be the same!");
} }
[TearDown]
public void TearDown()
{
// Stop, shutdown, and destroy
NetworkManagerHelper.ShutdownNetworkManager();
}
} }
} }

View File

@@ -0,0 +1,154 @@
using System.Collections;
using NUnit.Framework;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using UnityEngine.TestTools;
namespace Unity.Netcode.RuntimeTests
{
[TestFixture(HostOrServer.DAHost, true)]
[TestFixture(HostOrServer.DAHost, false)]
public class ExtendedNetworkShowAndHideTests : NetcodeIntegrationTest
{
protected override int NumberOfClients => 3;
private bool m_EnableSceneManagement;
private GameObject m_ObjectToSpawn;
private NetworkObject m_SpawnedObject;
private NetworkManager m_ClientToHideFrom;
private NetworkManager m_LateJoinClient;
private NetworkManager m_SpawnOwner;
public ExtendedNetworkShowAndHideTests(HostOrServer hostOrServer, bool enableSceneManagement) : base(hostOrServer)
{
m_EnableSceneManagement = enableSceneManagement;
}
protected override void OnServerAndClientsCreated()
{
if (!UseCMBService())
{
m_ServerNetworkManager.NetworkConfig.EnableSceneManagement = m_EnableSceneManagement;
}
foreach (var client in m_ClientNetworkManagers)
{
client.NetworkConfig.EnableSceneManagement = m_EnableSceneManagement;
}
m_ObjectToSpawn = CreateNetworkObjectPrefab("TestObject");
m_ObjectToSpawn.SetActive(false);
base.OnServerAndClientsCreated();
}
private bool AllClientsSpawnedObject()
{
if (!UseCMBService())
{
if (!s_GlobalNetworkObjects.ContainsKey(m_ServerNetworkManager.LocalClientId))
{
return false;
}
if (!s_GlobalNetworkObjects[m_ServerNetworkManager.LocalClientId].ContainsKey(m_SpawnedObject.NetworkObjectId))
{
return false;
}
}
foreach (var client in m_ClientNetworkManagers)
{
if (!s_GlobalNetworkObjects.ContainsKey(client.LocalClientId))
{
return false;
}
if (!s_GlobalNetworkObjects[client.LocalClientId].ContainsKey(m_SpawnedObject.NetworkObjectId))
{
return false;
}
}
return true;
}
private bool IsClientPromotedToSessionOwner()
{
if (!UseCMBService())
{
if (m_ServerNetworkManager.CurrentSessionOwner != m_ClientToHideFrom.LocalClientId)
{
return false;
}
}
foreach (var client in m_ClientNetworkManagers)
{
if (!client.IsConnectedClient)
{
continue;
}
if (client.CurrentSessionOwner != m_ClientToHideFrom.LocalClientId)
{
return false;
}
}
return true;
}
protected override void OnNewClientCreated(NetworkManager networkManager)
{
m_LateJoinClient = networkManager;
networkManager.NetworkConfig.EnableSceneManagement = m_EnableSceneManagement;
networkManager.NetworkConfig.Prefabs = m_SpawnOwner.NetworkConfig.Prefabs;
base.OnNewClientCreated(networkManager);
}
/// <summary>
/// This test validates the following NetworkShow - NetworkHide issue:
/// - During a session, a spawned object is hidden from a client.
/// - The current session owner disconnects and the client the object is hidden from is prommoted to the session owner.
/// - A new client joins and the newly promoted session owner synchronizes the newly joined client with only objects visible to it.
/// - Any already connected non-session owner client should "NetworkShow" the object to the newly connected client
/// (but only if the hidden object has SpawnWithObservers enabled)
/// </summary>
[UnityTest]
public IEnumerator HiddenObjectPromotedSessionOwnerNewClientSynchronizes()
{
// Get the test relative session owner
var sessionOwner = UseCMBService() ? m_ClientNetworkManagers[0] : m_ServerNetworkManager;
m_SpawnOwner = UseCMBService() ? m_ClientNetworkManagers[1] : m_ClientNetworkManagers[0];
m_ClientToHideFrom = UseCMBService() ? m_ClientNetworkManagers[NumberOfClients - 1] : m_ClientNetworkManagers[1];
m_ObjectToSpawn.SetActive(true);
// Spawn the object with a non-session owner client
m_SpawnedObject = SpawnObject(m_ObjectToSpawn, m_SpawnOwner).GetComponent<NetworkObject>();
yield return WaitForConditionOrTimeOut(AllClientsSpawnedObject);
AssertOnTimeout($"Not all clients spawned and instance of {m_SpawnedObject.name}");
// Hide the spawned object from the to be promoted session owner
m_SpawnedObject.NetworkHide(m_ClientToHideFrom.LocalClientId);
yield return WaitForConditionOrTimeOut(() => !m_ClientToHideFrom.SpawnManager.SpawnedObjects.ContainsKey(m_SpawnedObject.NetworkObjectId));
AssertOnTimeout($"{m_SpawnedObject.name} was not hidden from Client-{m_ClientToHideFrom.LocalClientId}!");
// Promoted a new session owner (DAHost promotes while CMB Session we disconnect the current session owner)
if (!UseCMBService())
{
m_ServerNetworkManager.PromoteSessionOwner(m_ClientToHideFrom.LocalClientId);
}
else
{
sessionOwner.Shutdown();
}
// Wait for the new session owner to be promoted and for all clients to acknowledge the promotion
yield return WaitForConditionOrTimeOut(IsClientPromotedToSessionOwner);
AssertOnTimeout($"Client-{m_ClientToHideFrom.LocalClientId} was not promoted as session owner on all client instances!");
// Connect a new client instance
yield return CreateAndStartNewClient();
// Assure the newly connected client is synchronized with the NetworkObject hidden from the newly promoted session owner
yield return WaitForConditionOrTimeOut(() => m_LateJoinClient.SpawnManager.SpawnedObjects.ContainsKey(m_SpawnedObject.NetworkObjectId));
AssertOnTimeout($"Client-{m_LateJoinClient.LocalClientId} never spawned {nameof(NetworkObject)} {m_SpawnedObject.name}!");
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a6389d04d9080b24b99de7e6900a064c

View File

@@ -239,5 +239,45 @@ namespace Unity.Netcode.RuntimeTests
}); });
} }
} }
[Test]
public unsafe void ErrorMessageIsPrintedWhenAttemptingToSendNamedMessageWithTooBigBuffer()
{
// First try a valid send with the maximum allowed size (this is atm 1264)
var msgSize = m_ServerNetworkManager.MessageManager.NonFragmentedMessageMaxSize - FastBufferWriter.GetWriteSize<NetworkMessageHeader>() - sizeof(ulong)/*MessageName hash*/ - sizeof(NetworkBatchHeader);
var bufferSize = m_ServerNetworkManager.MessageManager.NonFragmentedMessageMaxSize;
var messageName = Guid.NewGuid().ToString();
var messageContent = new byte[msgSize];
var writer = new FastBufferWriter(bufferSize, Allocator.Temp, bufferSize * 2);
using (writer)
{
writer.TryBeginWrite(msgSize);
writer.WriteBytes(messageContent, msgSize, 0);
m_ServerNetworkManager.CustomMessagingManager.SendNamedMessage(messageName, new List<ulong> { FirstClient.LocalClientId }, writer);
m_ServerNetworkManager.CustomMessagingManager.SendNamedMessage(messageName, FirstClient.LocalClientId, writer);
}
msgSize++;
messageContent = new byte[msgSize];
writer = new FastBufferWriter(bufferSize, Allocator.Temp, bufferSize * 2);
using (writer)
{
writer.TryBeginWrite(msgSize);
writer.WriteBytes(messageContent, msgSize, 0);
var message = Assert.Throws<OverflowException>(
() =>
{
m_ServerNetworkManager.CustomMessagingManager.SendNamedMessage(messageName, new List<ulong> { FirstClient.LocalClientId }, writer);
}).Message;
Assert.IsTrue(message.Contains($"Given message size ({msgSize} bytes) is greater than the maximum"), $"Unexpected exception: {message}");
message = Assert.Throws<OverflowException>(
() =>
{
m_ServerNetworkManager.CustomMessagingManager.SendNamedMessage(messageName, FirstClient.LocalClientId, writer);
}).Message;
Assert.IsTrue(message.Contains($"Given message size ({msgSize} bytes) is greater than the maximum"), $"Unexpected exception: {message}");
}
}
} }
} }

View File

@@ -194,5 +194,44 @@ namespace Unity.Netcode.RuntimeTests
}); });
} }
} }
[Test]
public unsafe void ErrorMessageIsPrintedWhenAttemptingToSendUnnamedMessageWithTooBigBuffer()
{
// First try a valid send with the maximum allowed size (this is atm 1272)
var msgSize = m_ServerNetworkManager.MessageManager.NonFragmentedMessageMaxSize - FastBufferWriter.GetWriteSize<NetworkMessageHeader>() - sizeof(NetworkBatchHeader);
var bufferSize = m_ServerNetworkManager.MessageManager.NonFragmentedMessageMaxSize;
var messageContent = new byte[msgSize];
var writer = new FastBufferWriter(bufferSize, Allocator.Temp, bufferSize * 2);
using (writer)
{
writer.TryBeginWrite(msgSize);
writer.WriteBytes(messageContent, msgSize, 0);
m_ServerNetworkManager.CustomMessagingManager.SendUnnamedMessage(new List<ulong> { FirstClient.LocalClientId }, writer);
m_ServerNetworkManager.CustomMessagingManager.SendUnnamedMessage(FirstClient.LocalClientId, writer);
}
msgSize++;
messageContent = new byte[msgSize];
writer = new FastBufferWriter(bufferSize, Allocator.Temp, bufferSize * 2);
using (writer)
{
writer.TryBeginWrite(msgSize);
writer.WriteBytes(messageContent, msgSize, 0);
var message = Assert.Throws<OverflowException>(
() =>
{
m_ServerNetworkManager.CustomMessagingManager.SendUnnamedMessage(new List<ulong> { FirstClient.LocalClientId }, writer);
}).Message;
Assert.IsTrue(message.Contains($"Given message size ({msgSize} bytes) is greater than the maximum"), $"Unexpected exception: {message}");
message = Assert.Throws<OverflowException>(
() =>
{
m_ServerNetworkManager.CustomMessagingManager.SendUnnamedMessage(FirstClient.LocalClientId, writer);
}).Message;
Assert.IsTrue(message.Contains($"Given message size ({msgSize} bytes) is greater than the maximum"), $"Unexpected exception: {message}");
}
}
} }
} }

View File

@@ -200,9 +200,8 @@ namespace Unity.Netcode.RuntimeTests
/// </summary> /// </summary>
/// <param name="testWithHost">Determines if we are running as a server or host</param> /// <param name="testWithHost">Determines if we are running as a server or host</param>
/// <param name="authority">Determines if we are using server or owner authority</param> /// <param name="authority">Determines if we are using server or owner authority</param>
public NetworkTransformBase(HostOrServer testWithHost, Authority authority, RotationCompression rotationCompression, Rotation rotation, Precision precision) public NetworkTransformBase(HostOrServer testWithHost, Authority authority, RotationCompression rotationCompression, Rotation rotation, Precision precision) : base(testWithHost)
{ {
m_UseHost = testWithHost == HostOrServer.Host;
m_Authority = authority; m_Authority = authority;
m_Precision = precision; m_Precision = precision;
m_RotationCompression = rotationCompression; m_RotationCompression = rotationCompression;
@@ -376,6 +375,18 @@ namespace Unity.Netcode.RuntimeTests
return true; return true;
} }
protected bool AllFirstLevelChildObjectInstancesHaveChild()
{
foreach (var instance in ChildObjectComponent.ClientInstances.Values)
{
if (instance.transform.parent == null)
{
return false;
}
}
return true;
}
protected bool AllChildObjectInstancesHaveChild() protected bool AllChildObjectInstancesHaveChild()
{ {
foreach (var instance in ChildObjectComponent.ClientInstances.Values) foreach (var instance in ChildObjectComponent.ClientInstances.Values)
@@ -398,6 +409,33 @@ namespace Unity.Netcode.RuntimeTests
return true; return true;
} }
protected bool AllFirstLevelChildObjectInstancesHaveNoParent()
{
foreach (var instance in ChildObjectComponent.ClientInstances.Values)
{
if (instance.transform.parent != null)
{
return false;
}
}
return true;
}
protected bool AllSubChildObjectInstancesHaveNoParent()
{
if (ChildObjectComponent.HasSubChild)
{
foreach (var instance in ChildObjectComponent.ClientSubChildInstances.Values)
{
if (instance.transform.parent != null)
{
return false;
}
}
}
return true;
}
/// <summary> /// <summary>
/// A wait condition specific method that assures the local space coordinates /// A wait condition specific method that assures the local space coordinates
/// are not impacted by NetworkTransform when parented. /// are not impacted by NetworkTransform when parented.

View File

@@ -101,6 +101,225 @@ namespace Unity.Netcode.RuntimeTests
} }
#if !MULTIPLAYER_TOOLS #if !MULTIPLAYER_TOOLS
private void UpdateTransformLocal(Components.NetworkTransform networkTransformTestComponent)
{
networkTransformTestComponent.transform.localPosition += GetRandomVector3(0.5f, 2.0f);
var rotation = networkTransformTestComponent.transform.localRotation;
var eulerRotation = rotation.eulerAngles;
eulerRotation += GetRandomVector3(0.5f, 5.0f);
rotation.eulerAngles = eulerRotation;
networkTransformTestComponent.transform.localRotation = rotation;
}
private void UpdateTransformWorld(Components.NetworkTransform networkTransformTestComponent)
{
networkTransformTestComponent.transform.position += GetRandomVector3(0.5f, 2.0f);
var rotation = networkTransformTestComponent.transform.rotation;
var eulerRotation = rotation.eulerAngles;
eulerRotation += GetRandomVector3(0.5f, 5.0f);
rotation.eulerAngles = eulerRotation;
networkTransformTestComponent.transform.rotation = rotation;
}
/// <summary>
/// This test validates the SwitchTransformSpaceWhenParented setting under all network topologies
/// </summary>
[Test]
public void SwitchTransformSpaceWhenParentedTest([Values(0.5f, 1.0f, 5.0f)] float scale)
{
m_UseParentingThreshold = true;
// Get the NetworkManager that will have authority in order to spawn with the correct authority
var isServerAuthority = m_Authority == Authority.ServerAuthority;
var authorityNetworkManager = m_ServerNetworkManager;
if (!isServerAuthority)
{
authorityNetworkManager = m_ClientNetworkManagers[0];
}
var childAuthorityNetworkManager = m_ClientNetworkManagers[0];
if (!isServerAuthority)
{
childAuthorityNetworkManager = m_ServerNetworkManager;
}
// Spawn a parent and children
ChildObjectComponent.HasSubChild = true;
// Modify our prefabs for this specific test
m_ParentObject.GetComponent<NetworkTransformTestComponent>().TickSyncChildren = true;
m_ChildObject.GetComponent<ChildObjectComponent>().SwitchTransformSpaceWhenParented = true;
m_ChildObject.GetComponent<ChildObjectComponent>().TickSyncChildren = true;
m_SubChildObject.GetComponent<ChildObjectComponent>().SwitchTransformSpaceWhenParented = true;
m_SubChildObject.GetComponent<ChildObjectComponent>().TickSyncChildren = true;
m_ChildObject.AllowOwnerToParent = true;
m_SubChildObject.AllowOwnerToParent = true;
var authoritySideParent = SpawnObject(m_ParentObject.gameObject, authorityNetworkManager).GetComponent<NetworkObject>();
var authoritySideChild = SpawnObject(m_ChildObject.gameObject, childAuthorityNetworkManager).GetComponent<NetworkObject>();
var authoritySideSubChild = SpawnObject(m_SubChildObject.gameObject, childAuthorityNetworkManager).GetComponent<NetworkObject>();
// Assure all of the child object instances are spawned before proceeding to parenting
var success = WaitForConditionOrTimeOutWithTimeTravel(AllChildObjectInstancesAreSpawned);
Assert.True(success, "Timed out waiting for all child instances to be spawned!");
// Get the owner instance if in client-server mode with owner authority
if (m_Authority == Authority.OwnerAuthority && !m_DistributedAuthority)
{
authoritySideParent = s_GlobalNetworkObjects[authoritySideParent.OwnerClientId][authoritySideParent.NetworkObjectId];
authoritySideChild = s_GlobalNetworkObjects[authoritySideChild.OwnerClientId][authoritySideChild.NetworkObjectId];
authoritySideSubChild = s_GlobalNetworkObjects[authoritySideSubChild.OwnerClientId][authoritySideSubChild.NetworkObjectId];
}
// Get the authority parent and child instances
m_AuthorityParentObject = NetworkTransformTestComponent.AuthorityInstance.NetworkObject;
m_AuthorityChildObject = ChildObjectComponent.AuthorityInstance.NetworkObject;
m_AuthoritySubChildObject = ChildObjectComponent.AuthoritySubInstance.NetworkObject;
// The child NetworkTransform will use world space when world position stays and
// local space when world position does not stay when parenting.
ChildObjectComponent.AuthorityInstance.UseHalfFloatPrecision = m_Precision == Precision.Half;
ChildObjectComponent.AuthorityInstance.UseQuaternionSynchronization = m_Rotation == Rotation.Quaternion;
ChildObjectComponent.AuthorityInstance.UseQuaternionCompression = m_RotationCompression == RotationCompression.QuaternionCompress;
ChildObjectComponent.AuthoritySubInstance.UseHalfFloatPrecision = m_Precision == Precision.Half;
ChildObjectComponent.AuthoritySubInstance.UseQuaternionSynchronization = m_Rotation == Rotation.Quaternion;
ChildObjectComponent.AuthoritySubInstance.UseQuaternionCompression = m_RotationCompression == RotationCompression.QuaternionCompress;
// Set whether we are interpolating or not
m_AuthorityParentNetworkTransform = m_AuthorityParentObject.GetComponent<NetworkTransformTestComponent>();
m_AuthorityParentNetworkTransform.Interpolate = true;
m_AuthorityChildNetworkTransform = m_AuthorityChildObject.GetComponent<ChildObjectComponent>();
m_AuthorityChildNetworkTransform.Interpolate = true;
m_AuthoritySubChildNetworkTransform = m_AuthoritySubChildObject.GetComponent<ChildObjectComponent>();
m_AuthoritySubChildNetworkTransform.Interpolate = true;
// Apply a scale to the parent object to make sure the scale on the child is properly updated on
// non-authority instances.
var halfScale = scale * 0.5f;
m_AuthorityParentObject.transform.localScale = GetRandomVector3(scale - halfScale, scale + halfScale);
m_AuthorityChildObject.transform.localScale = GetRandomVector3(scale - halfScale, scale + halfScale);
m_AuthoritySubChildObject.transform.localScale = GetRandomVector3(scale - halfScale, scale + halfScale);
// Allow one tick for authority to update these changes
TimeTravelAdvanceTick();
success = WaitForConditionOrTimeOutWithTimeTravel(PositionRotationScaleMatches);
Assert.True(success, "All transform values did not match prior to parenting!");
success = WaitForConditionOrTimeOutWithTimeTravel(PositionRotationScaleMatches);
Assert.True(success, "All transform values did not match prior to parenting!");
// Move things around while parenting and removing the parent
// Not the absolute "perfect" test, but it validates the clients all synchronize
// parenting and transform values.
for (int i = 0; i < 30; i++)
{
// Provide two network ticks for interpolation to finalize
TimeTravelAdvanceTick();
TimeTravelAdvanceTick();
// This validates each child instance has preserved their local space values
AllChildrenLocalTransformValuesMatch(false, ChildrenTransformCheckType.Connected_Clients);
// This validates each sub-child instance has preserved their local space values
AllChildrenLocalTransformValuesMatch(true, ChildrenTransformCheckType.Connected_Clients);
// Parent while in motion
if (i == 5)
{
// Parent the child under the parent with the current world position stays setting
Assert.True(authoritySideChild.TrySetParent(authoritySideParent.transform), $"[Child][Client-{authoritySideChild.NetworkManagerOwner.LocalClientId}] Failed to set child's parent!");
// This waits for all child instances to be parented
success = WaitForConditionOrTimeOutWithTimeTravel(AllFirstLevelChildObjectInstancesHaveChild, 300);
Assert.True(success, "Timed out waiting for all instances to have parented a child!");
}
if (i == 10)
{
// Parent the sub-child under the child with the current world position stays setting
Assert.True(authoritySideSubChild.TrySetParent(authoritySideChild.transform), $"[Sub-Child][Client-{authoritySideSubChild.NetworkManagerOwner.LocalClientId}] Failed to set sub-child's parent!");
// This waits for all child instances to be parented
success = WaitForConditionOrTimeOutWithTimeTravel(AllChildObjectInstancesHaveChild, 300);
Assert.True(success, "Timed out waiting for all instances to have parented a child!");
}
if (i == 15)
{
// Verify that a late joining client will synchronize to the parented NetworkObjects properly
CreateAndStartNewClientWithTimeTravel();
// Assure all of the child object instances are spawned (basically for the newly connected client)
success = WaitForConditionOrTimeOutWithTimeTravel(AllChildObjectInstancesAreSpawned, 300);
Assert.True(success, "Timed out waiting for all child instances to be spawned!");
// This waits for all child instances to be parented
success = WaitForConditionOrTimeOutWithTimeTravel(AllChildObjectInstancesHaveChild, 300);
Assert.True(success, "Timed out waiting for all instances to have parented a child!");
// This validates each child instance has preserved their local space values
AllChildrenLocalTransformValuesMatch(false, ChildrenTransformCheckType.Late_Join_Client);
// This validates each sub-child instance has preserved their local space values
AllChildrenLocalTransformValuesMatch(true, ChildrenTransformCheckType.Late_Join_Client);
}
if (i == 20)
{
// Remove the parent
Assert.True(authoritySideSubChild.TryRemoveParent(), $"[Sub-Child][Client-{authoritySideSubChild.NetworkManagerOwner.LocalClientId}] Failed to set sub-child's parent!");
// This waits for all child instances to have the parent removed
success = WaitForConditionOrTimeOutWithTimeTravel(AllSubChildObjectInstancesHaveNoParent, 300);
Assert.True(success, "Timed out waiting for all instances remove the parent!");
}
if (i == 25)
{
// Parent the child under the parent with the current world position stays setting
Assert.True(authoritySideChild.TryRemoveParent(), $"[Child][Client-{authoritySideChild.NetworkManagerOwner.LocalClientId}] Failed to remove parent!");
// This waits for all child instances to be parented
success = WaitForConditionOrTimeOutWithTimeTravel(AllFirstLevelChildObjectInstancesHaveNoParent, 300);
Assert.True(success, "Timed out waiting for all instances remove the parent!");
}
UpdateTransformWorld(m_AuthorityParentNetworkTransform);
if (m_AuthorityChildNetworkTransform.InLocalSpace)
{
UpdateTransformLocal(m_AuthorityChildNetworkTransform);
}
else
{
UpdateTransformWorld(m_AuthorityChildNetworkTransform);
}
if (m_AuthoritySubChildNetworkTransform.InLocalSpace)
{
UpdateTransformLocal(m_AuthoritySubChildNetworkTransform);
}
else
{
UpdateTransformWorld(m_AuthoritySubChildNetworkTransform);
}
}
success = WaitForConditionOrTimeOutWithTimeTravel(PositionRotationScaleMatches, 300);
Assert.True(success, "All transform values did not match prior to parenting!");
// Revert the modifications made for this specific test
m_ParentObject.GetComponent<NetworkTransformTestComponent>().TickSyncChildren = false;
m_ChildObject.GetComponent<ChildObjectComponent>().SwitchTransformSpaceWhenParented = false;
m_ChildObject.GetComponent<ChildObjectComponent>().TickSyncChildren = false;
m_ChildObject.AllowOwnerToParent = false;
m_SubChildObject.AllowOwnerToParent = false;
m_SubChildObject.GetComponent<ChildObjectComponent>().SwitchTransformSpaceWhenParented = false;
m_SubChildObject.GetComponent<ChildObjectComponent>().TickSyncChildren = false;
}
/// <summary> /// <summary>
/// Validates that transform values remain the same when a NetworkTransform is /// Validates that transform values remain the same when a NetworkTransform is
/// parented under another NetworkTransform under all of the possible axial conditions /// parented under another NetworkTransform under all of the possible axial conditions
@@ -410,6 +629,7 @@ namespace Unity.Netcode.RuntimeTests
Assert.AreEqual(Vector3.zero, m_NonAuthoritativeTransform.transform.position, "server side pos should be zero at first"); // sanity check Assert.AreEqual(Vector3.zero, m_NonAuthoritativeTransform.transform.position, "server side pos should be zero at first"); // sanity check
TimeTravelAdvanceTick(); TimeTravelAdvanceTick();
TimeTravelToNextTick();
m_AuthoritativeTransform.StatePushed = false; m_AuthoritativeTransform.StatePushed = false;
var nextPosition = GetRandomVector3(2f, 30f); var nextPosition = GetRandomVector3(2f, 30f);

View File

@@ -299,16 +299,15 @@ namespace Unity.Netcode.RuntimeTests
}, new List<NetworkManager> { m_ServerNetworkManager }); }, new List<NetworkManager> { m_ServerNetworkManager });
WaitForMessageReceivedWithTimeTravel<NetworkTransformMessage>(m_ClientNetworkManagers.ToList()); WaitForMessageReceivedWithTimeTravel<NetworkTransformMessage>(m_ClientNetworkManagers.ToList());
var percentChanged = 1f / 60f; var percentChanged = 1f / 60f;
AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.transform.position); AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.transform.position);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.transform.localScale); AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.transform.localScale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.transform.rotation); AssertQuaternionsAreEquivalent(Quaternion.Lerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.transform.rotation);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.AnticipatedState.Position); AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.AnticipatedState.Position);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.AnticipatedState.Scale); AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.AnticipatedState.Scale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.AnticipatedState.Rotation); AssertQuaternionsAreEquivalent(Quaternion.Lerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.AnticipatedState.Rotation);
AssertVectorsAreEquivalent(serverSetPosition, testComponent.AuthoritativeState.Position); AssertVectorsAreEquivalent(serverSetPosition, testComponent.AuthoritativeState.Position);
AssertVectorsAreEquivalent(serverSetScale, testComponent.AuthoritativeState.Scale); AssertVectorsAreEquivalent(serverSetScale, testComponent.AuthoritativeState.Scale);
@@ -316,11 +315,11 @@ namespace Unity.Netcode.RuntimeTests
AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.transform.position); AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.transform.position);
AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.transform.localScale); AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.transform.localScale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.transform.rotation); AssertQuaternionsAreEquivalent(Quaternion.Lerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.transform.rotation);
AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.AnticipatedState.Position); AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.AnticipatedState.Position);
AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.AnticipatedState.Scale); AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.AnticipatedState.Scale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.AnticipatedState.Rotation); AssertQuaternionsAreEquivalent(Quaternion.Lerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.AnticipatedState.Rotation);
AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AuthoritativeState.Position); AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AuthoritativeState.Position);
AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AuthoritativeState.Scale); AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AuthoritativeState.Scale);
@@ -333,11 +332,11 @@ namespace Unity.Netcode.RuntimeTests
AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.transform.position); AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.transform.position);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.transform.localScale); AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.transform.localScale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.transform.rotation); AssertQuaternionsAreEquivalent(Quaternion.Lerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.transform.rotation);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.AnticipatedState.Position); AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.AnticipatedState.Position);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.AnticipatedState.Scale); AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.AnticipatedState.Scale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.AnticipatedState.Rotation); AssertQuaternionsAreEquivalent(Quaternion.Lerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.AnticipatedState.Rotation);
AssertVectorsAreEquivalent(serverSetPosition, testComponent.AuthoritativeState.Position); AssertVectorsAreEquivalent(serverSetPosition, testComponent.AuthoritativeState.Position);
AssertVectorsAreEquivalent(serverSetScale, testComponent.AuthoritativeState.Scale); AssertVectorsAreEquivalent(serverSetScale, testComponent.AuthoritativeState.Scale);
@@ -345,11 +344,11 @@ namespace Unity.Netcode.RuntimeTests
AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.transform.position); AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.transform.position);
AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.transform.localScale); AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.transform.localScale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.transform.rotation); AssertQuaternionsAreEquivalent(Quaternion.Lerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.transform.rotation);
AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.AnticipatedState.Position); AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.AnticipatedState.Position);
AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.AnticipatedState.Scale); AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.AnticipatedState.Scale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.AnticipatedState.Rotation); AssertQuaternionsAreEquivalent(Quaternion.Lerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.AnticipatedState.Rotation);
AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AuthoritativeState.Position); AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AuthoritativeState.Position);
AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AuthoritativeState.Scale); AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AuthoritativeState.Scale);

View File

@@ -14,9 +14,11 @@ namespace Unity.Netcode.RuntimeTests
internal class NetworkVisibilityTests : NetcodeIntegrationTest internal class NetworkVisibilityTests : NetcodeIntegrationTest
{ {
protected override int NumberOfClients => 1; protected override int NumberOfClients => 2;
private GameObject m_TestNetworkPrefab; private GameObject m_TestNetworkPrefab;
private bool m_SceneManagementEnabled; private bool m_SceneManagementEnabled;
private GameObject m_SpawnedObject;
private NetworkManager m_SessionOwner;
public NetworkVisibilityTests(SceneManagementState sceneManagementState, NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) public NetworkVisibilityTests(SceneManagementState sceneManagementState, NetworkTopologyTypes networkTopologyType) : base(networkTopologyType)
{ {
@@ -27,7 +29,11 @@ namespace Unity.Netcode.RuntimeTests
{ {
m_TestNetworkPrefab = CreateNetworkObjectPrefab("Object"); m_TestNetworkPrefab = CreateNetworkObjectPrefab("Object");
m_TestNetworkPrefab.AddComponent<NetworkVisibilityComponent>(); m_TestNetworkPrefab.AddComponent<NetworkVisibilityComponent>();
if (!UseCMBService())
{
m_ServerNetworkManager.NetworkConfig.EnableSceneManagement = m_SceneManagementEnabled; m_ServerNetworkManager.NetworkConfig.EnableSceneManagement = m_SceneManagementEnabled;
}
foreach (var clientNetworkManager in m_ClientNetworkManagers) foreach (var clientNetworkManager in m_ClientNetworkManagers)
{ {
clientNetworkManager.NetworkConfig.EnableSceneManagement = m_SceneManagementEnabled; clientNetworkManager.NetworkConfig.EnableSceneManagement = m_SceneManagementEnabled;
@@ -38,7 +44,8 @@ namespace Unity.Netcode.RuntimeTests
protected override IEnumerator OnServerAndClientsConnected() protected override IEnumerator OnServerAndClientsConnected()
{ {
SpawnObject(m_TestNetworkPrefab, m_ServerNetworkManager); m_SessionOwner = UseCMBService() ? m_ClientNetworkManagers[0] : m_ServerNetworkManager;
m_SpawnedObject = SpawnObject(m_TestNetworkPrefab, m_SessionOwner);
yield return base.OnServerAndClientsConnected(); yield return base.OnServerAndClientsConnected();
} }
@@ -46,13 +53,49 @@ namespace Unity.Netcode.RuntimeTests
[UnityTest] [UnityTest]
public IEnumerator HiddenObjectsTest() public IEnumerator HiddenObjectsTest()
{ {
var expectedCount = UseCMBService() ? 2 : 3;
#if UNITY_2023_1_OR_NEWER #if UNITY_2023_1_OR_NEWER
yield return WaitForConditionOrTimeOut(() => Object.FindObjectsByType<NetworkVisibilityComponent>(FindObjectsSortMode.None).Where((c) => c.IsSpawned).Count() == 2); yield return WaitForConditionOrTimeOut(() => Object.FindObjectsByType<NetworkVisibilityComponent>(FindObjectsSortMode.None).Where((c) => c.IsSpawned).Count() == expectedCount);
#else #else
yield return WaitForConditionOrTimeOut(() => Object.FindObjectsOfType<NetworkVisibilityComponent>().Where((c) => c.IsSpawned).Count() == 2); yield return WaitForConditionOrTimeOut(() => Object.FindObjectsOfType<NetworkVisibilityComponent>().Where((c) => c.IsSpawned).Count() == expectedCount);
#endif #endif
Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, "Timed out waiting for the visible object count to equal 2!"); Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, "Timed out waiting for the visible object count to equal 2!");
} }
[UnityTest]
public IEnumerator HideShowAndDeleteTest()
{
var expectedCount = UseCMBService() ? 2 : 3;
#if UNITY_2023_1_OR_NEWER
yield return WaitForConditionOrTimeOut(() => Object.FindObjectsByType<NetworkVisibilityComponent>(FindObjectsSortMode.None).Where((c) => c.IsSpawned).Count() == expectedCount);
#else
yield return WaitForConditionOrTimeOut(() => Object.FindObjectsOfType<NetworkVisibilityComponent>().Where((c) => c.IsSpawned).Count() == expectedCount);
#endif
AssertOnTimeout("Timed out waiting for the visible object count to equal 2!");
var sessionOwnerNetworkObject = m_SpawnedObject.GetComponent<NetworkObject>();
var clientIndex = UseCMBService() ? 1 : 0;
sessionOwnerNetworkObject.NetworkHide(m_ClientNetworkManagers[clientIndex].LocalClientId);
#if UNITY_2023_1_OR_NEWER
yield return WaitForConditionOrTimeOut(() => Object.FindObjectsByType<NetworkVisibilityComponent>(FindObjectsSortMode.None).Where((c) => c.IsSpawned).Count() == expectedCount - 1);
#else
yield return WaitForConditionOrTimeOut(() => Object.FindObjectsOfType<NetworkVisibilityComponent>().Where((c) => c.IsSpawned).Count() == expectedCount - 1);
#endif
AssertOnTimeout($"Timed out waiting for {m_SpawnedObject.name} to be hidden from client!");
var networkObjectId = sessionOwnerNetworkObject.NetworkObjectId;
sessionOwnerNetworkObject.NetworkShow(m_ClientNetworkManagers[clientIndex].LocalClientId);
sessionOwnerNetworkObject.Despawn(true);
// Expect no exceptions
yield return s_DefaultWaitForTick;
// Now force a scenario where it normally would have caused an exception
m_SessionOwner.SpawnManager.ObjectsToShowToClient.Add(m_ClientNetworkManagers[clientIndex].LocalClientId, new System.Collections.Generic.List<NetworkObject>());
m_SessionOwner.SpawnManager.ObjectsToShowToClient[m_ClientNetworkManagers[clientIndex].LocalClientId].Add(null);
// Expect no exceptions
yield return s_DefaultWaitForTick;
}
} }
} }

View File

@@ -63,14 +63,10 @@ namespace Unity.Netcode.RuntimeTests
private const int k_MaxThresholdFailures = 4; private const int k_MaxThresholdFailures = 4;
private int m_ExceededThresholdCount; private int m_ExceededThresholdCount;
private void Update() public override void OnUpdate()
{ {
base.OnUpdate(); base.OnUpdate();
if (!IsSpawned || TestComplete)
{
return;
}
// Check the position of the nested object on the client // Check the position of the nested object on the client
if (CheckPosition) if (CheckPosition)
@@ -92,6 +88,17 @@ namespace Unity.Netcode.RuntimeTests
m_ExceededThresholdCount = 0; m_ExceededThresholdCount = 0;
} }
} }
}
private void Update()
{
base.OnUpdate();
if (!IsSpawned || !CanCommitToTransform || TestComplete)
{
return;
}
// Move the nested object on the server // Move the nested object on the server
if (IsMoving) if (IsMoving)
@@ -136,7 +143,6 @@ namespace Unity.Netcode.RuntimeTests
Assert.True(CanCommitToTransform, $"Using non-authority instance to update transform!"); Assert.True(CanCommitToTransform, $"Using non-authority instance to update transform!");
transform.position = new Vector3(1000.0f, 1000.0f, 1000.0f); transform.position = new Vector3(1000.0f, 1000.0f, 1000.0f);
} }
} }
} }

View File

@@ -2,23 +2,23 @@
"name": "com.unity.netcode.gameobjects", "name": "com.unity.netcode.gameobjects",
"displayName": "Netcode for GameObjects", "displayName": "Netcode for GameObjects",
"description": "Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer.", "description": "Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer.",
"version": "2.0.0-pre.4", "version": "2.0.0",
"unity": "6000.0", "unity": "6000.0",
"dependencies": { "dependencies": {
"com.unity.nuget.mono-cecil": "1.11.4", "com.unity.nuget.mono-cecil": "1.11.4",
"com.unity.transport": "2.3.0" "com.unity.transport": "2.3.0"
}, },
"_upm": { "_upm": {
"changelog": "### Added\n\n- Added `NetworkVariable.CheckDirtyState` that is to be used in tandem with collections in order to detect whether the collection or an item within the collection has changed. (#3004)\n\n### Fixed\n\n- Fixed issue where nested `NetworkTransform` components were not getting updated. (#3016)\n- Fixed issue by adding null checks in `NetworkVariableBase.CanClientRead` and `NetworkVariableBase.CanClientWrite` methods to ensure safe access to `NetworkBehaviour`. (#3012)\n- Fixed issue where `FixedStringSerializer<T>` was using `NetworkVariableSerialization<byte>.AreEqual` to determine if two bytes were equal causes an exception to be thrown due to no byte serializer having been defined. (#3009)\n- Fixed Issue where a state with dual triggers, inbound and outbound, could cause a false layer to layer state transition message to be sent to non-authority `NetworkAnimator` instances and cause a warning message to be logged. (#3008)\n- Fixed issue using collections within `NetworkVariable` where the collection would not detect changes to items or nested items. (#3004)\n- Fixed issue where `List`, `Dictionary`, and `HashSet` collections would not uniquely duplicate nested collections. (#3004)\n- Fixed issue where `NotAuthorityTarget` would include the service observer in the list of targets to send the RPC to as opposed to excluding the service observer as it should. (#3000)\n- Fixed issue where `ProxyRpcTargetGroup` could attempt to send a message if there were no targets to send to. (#3000)\n\n### Changed\n\n- Changed `NetworkAnimator` to automatically switch to owner authoritative mode when using a distributed authority network topology. (#3021)\n- Changed permissions exception thrown in `NetworkList` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)\n- Changed permissions exception thrown in `NetworkVariable.Value` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)" "changelog": "### Added\n\n- Added tooltips for all of the `NetworkObject` component's properties. (#3052)\n- Added message size validation to named and unnamed message sending functions for better error messages. (#3049)\n- Added \"Check for NetworkObject Component\" property to the Multiplayer->Netcode for GameObjects project settings. When disabled, this will bypass the in-editor `NetworkObject` check on `NetworkBehaviour` components. (#3031)\n- Added `NetworkTransform.SwitchTransformSpaceWhenParented` property that, when enabled, will handle the world to local, local to world, and local to local transform space transitions when interpolation is enabled. (#3013)\n- Added `NetworkTransform.TickSyncChildren` that, when enabled, will tick synchronize nested and/or child `NetworkTransform` components to eliminate any potential visual jittering that could occur if the `NetworkTransform` instances get into a state where their state updates are landing on different network ticks. (#3013)\n- Added `NetworkObject.AllowOwnerToParent` property to provide the ability to allow clients to parent owned objects when running in a client-server network topology. (#3013)\n- Added `NetworkObject.SyncOwnerTransformWhenParented` property to provide a way to disable applying the server's transform information in the parenting message on the client owner instance which can be useful for owner authoritative motion models. (#3013)\n- Added `NetcodeEditorBase` editor helper class to provide easier modification and extension of the SDK's components. (#3013)\n\n### Fixed\n\n- Fixed issue where `NetworkAnimator` would send updates to non-observer clients. (#3057)\n- Fixed issue where an exception could occur when receiving a universal RPC for a `NetworkObject` that has been despawned. (#3052)\n- Fixed issue where a NetworkObject hidden from a client that is then promoted to be session owner was not being synchronized with newly joining clients.(#3051)\n- Fixed issue where clients could have a wrong time delta on `NetworkVariableBase` which could prevent from sending delta state updates. (#3045)\n- Fixed issue where setting a prefab hash value during connection approval but not having a player prefab assigned could cause an exception when spawning a player. (#3042)\n- Fixed issue where the `NetworkSpawnManager.HandleNetworkObjectShow` could throw an exception if one of the `NetworkObject` components to show was destroyed during the same frame. (#3030)\n- Fixed issue where the `NetworkManagerHelper` was continuing to check for hierarchy changes when in play mode. (#3026)\n- Fixed issue with newly/late joined clients and `NetworkTransform` synchronization of parented `NetworkObject` instances. (#3013)\n- Fixed issue with smooth transitions between transform spaces when interpolation is enabled (requires `NetworkTransform.SwitchTransformSpaceWhenParented` to be enabled). (#3013)\n\n### Changed\n\n- Changed `NetworkTransformEditor` now uses `NetworkTransform` as the base type class to assure it doesn't display a foldout group when using the base `NetworkTransform` component class. (#3052)\n- Changed `NetworkAnimator.Awake` is now a protected virtual method. (#3052)\n- Changed when invoking `NetworkManager.ConnectionManager.DisconnectClient` during a distributed authority session a more appropriate message is logged. (#3052)\n- Changed `NetworkTransformEditor` so it now derives from `NetcodeEditorBase`. (#3013)\n- Changed `NetworkRigidbodyBaseEditor` so it now derives from `NetcodeEditorBase`. (#3013)\n- Changed `NetworkManagerEditor` so it now derives from `NetcodeEditorBase`. (#3013)"
}, },
"upmCi": { "upmCi": {
"footprint": "48286e9f7b0e053fe7f7b524bafc69a99c2906fc" "footprint": "f1ef7566b7a89b1ee9c34cc13400735ae63964d4"
}, },
"documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.0/manual/index.html", "documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.0/manual/index.html",
"repository": { "repository": {
"url": "https://github.com/Unity-Technologies/com.unity.netcode.gameobjects.git", "url": "https://github.com/Unity-Technologies/com.unity.netcode.gameobjects.git",
"type": "git", "type": "git",
"revision": "2802dfcd13c3be1ac356191cc87d1559203d2db3" "revision": "8a7ae9f91a53bdcabe5e7df783dd1884c07bcd6f"
}, },
"samples": [ "samples": [
{ {