diff --git a/com.unity.netcode.gameobjects/Runtime/Components/NetworkTransform.cs b/com.unity.netcode.gameobjects/Runtime/Components/NetworkTransform.cs index 7c44ba13cb..3693a0afd4 100644 --- a/com.unity.netcode.gameobjects/Runtime/Components/NetworkTransform.cs +++ b/com.unity.netcode.gameobjects/Runtime/Components/NetworkTransform.cs @@ -3554,7 +3554,7 @@ protected internal override void InternalOnNetworkPostSpawn() } // Standard non-authority synchronization is handled here - if (!CanCommitToTransform && NetworkManager.IsConnectedClient && SynchronizeState.IsSynchronizing) + if (!CanCommitToTransform && m_CachedNetworkManager.IsConnectedClient && SynchronizeState.IsSynchronizing) { NonAuthorityFinalizeSynchronization(); } @@ -3625,9 +3625,9 @@ private void CleanUpOnDestroyOrDespawn() #else var forUpdate = true; #endif - if (m_CachedNetworkObject != null) + if (m_CachedNetworkObject) { - NetworkManager?.NetworkTransformRegistration(m_CachedNetworkObject, forUpdate, false); + m_CachedNetworkManager?.NetworkTransformRegistration(m_CachedNetworkObject, forUpdate, false); } DeregisterForTickUpdate(this); @@ -3673,7 +3673,7 @@ protected virtual void OnInitialize(ref NetworkVariable r /// private void ResetInterpolatedStateToCurrentAuthoritativeState() { - var serverTime = NetworkManager.ServerTime.Time; + var serverTime = m_CachedNetworkManager.ServerTime.Time; #if COM_UNITY_MODULES_PHYSICS || COM_UNITY_MODULES_PHYSICS2D var position = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetPosition() : GetSpaceRelativePosition(); var rotation = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetRotation() : GetSpaceRelativeRotation(); @@ -3695,7 +3695,7 @@ private void ResetInterpolatedStateToCurrentAuthoritativeState() } private NetworkObject m_CachedNetworkObject; /// - /// The internal initialzation method to allow for internal API adjustments + /// The internal initialization method to allow for internal API adjustments /// /// private void InternalInitialization(bool isOwnershipChange = false) @@ -3707,7 +3707,7 @@ private void InternalInitialization(bool isOwnershipChange = false) m_CachedNetworkObject = NetworkObject; // Determine if this is the first NetworkTransform in the associated NetworkObject's list - m_IsFirstNetworkTransform = NetworkObject.NetworkTransforms[0] == this; + m_IsFirstNetworkTransform = m_CachedNetworkObject.NetworkTransforms[0] == this; if (m_CachedNetworkManager && m_CachedNetworkManager.DistributedAuthorityMode) { @@ -3719,7 +3719,7 @@ private void InternalInitialization(bool isOwnershipChange = false) { if (CanCommitToTransform) { - if (NetworkObject.HasParentNetworkObject(transform)) + if (m_CachedNetworkObject.HasParentNetworkObject(transform)) { InLocalSpace = true; } @@ -3763,7 +3763,7 @@ private void InternalInitialization(bool isOwnershipChange = false) if (CanCommitToTransform) { // Make sure authority doesn't get added to updates (no need to do this on the authority side) - m_CachedNetworkManager.NetworkTransformRegistration(NetworkObject, forUpdate, false); + m_CachedNetworkManager.NetworkTransformRegistration(m_CachedNetworkObject, forUpdate, false); if (UseHalfFloatPrecision) { m_HalfPositionState = new NetworkDeltaPosition(currentPosition, m_CachedNetworkManager.ServerTime.Tick, math.bool3(SyncPositionX, SyncPositionY, SyncPositionZ)); @@ -3792,7 +3792,7 @@ private void InternalInitialization(bool isOwnershipChange = false) m_PreviousScaleLerpSmoothing = ScaleLerpSmoothing; // Non-authority needs to be added to updates for interpolation and applying state purposes - m_CachedNetworkManager.NetworkTransformRegistration(NetworkObject, forUpdate, true); + m_CachedNetworkManager.NetworkTransformRegistration(m_CachedNetworkObject, forUpdate, true); // Remove this instance from the tick update DeregisterForTickUpdate(this); ResetInterpolatedStateToCurrentAuthoritativeState(); @@ -3890,7 +3890,7 @@ private void DefaultParentChanged() m_RotationInterpolator.Clear(); // Always use NetworkManager here as this can be invoked prior to spawning - var tempTime = new NetworkTime(NetworkManager.NetworkConfig.TickRate, NetworkManager.ServerTime.Tick).Time; + var tempTime = new NetworkTime(NetworkManager.NetworkConfig.TickRate, m_CachedNetworkManager.ServerTime.Tick).Time; UpdatePositionInterpolator(m_InternalCurrentPosition, tempTime, true); m_ScaleInterpolator.ResetTo(m_InternalCurrentScale, tempTime); m_RotationInterpolator.ResetTo(m_InternalCurrentRotation, tempTime); @@ -3922,7 +3922,7 @@ internal override void InternalOnNetworkObjectParentChanged(NetworkObject parent if (LastTickSync == m_LocalAuthoritativeNetworkState.GetNetworkTick()) { m_InternalCurrentPosition = m_LastStateTargetPosition = GetSpaceRelativePosition(); - m_PositionInterpolator.ResetTo(m_PositionInterpolator.Parent, m_InternalCurrentPosition, NetworkManager.ServerTime.Time); + m_PositionInterpolator.ResetTo(m_PositionInterpolator.Parent, m_InternalCurrentPosition, m_CachedNetworkManager.ServerTime.Time); if (InLocalSpace) { transform.localPosition = m_InternalCurrentPosition; @@ -3954,7 +3954,7 @@ internal override void InternalOnNetworkObjectParentChanged(NetworkObject parent { m_InternalCurrentRotation = GetSpaceRelativeRotation(); m_TargetRotation = m_InternalCurrentRotation.eulerAngles; - m_RotationInterpolator.ResetTo(m_RotationInterpolator.Parent, m_InternalCurrentRotation, NetworkManager.ServerTime.Time); + m_RotationInterpolator.ResetTo(m_RotationInterpolator.Parent, m_InternalCurrentRotation, m_CachedNetworkManager.ServerTime.Time); if (InLocalSpace) { transform.localRotation = m_InternalCurrentRotation; @@ -4638,13 +4638,13 @@ private void UpdateTransformState() { continue; } - NetworkManager.MessageManager.SendMessage(ref m_OutboundMessage, networkDelivery, clientId); + m_CachedNetworkManager.MessageManager.SendMessage(ref m_OutboundMessage, networkDelivery, clientId); } } else { // Clients (owner authoritative) send messages to the server-host - NetworkManager.MessageManager.SendMessage(ref m_OutboundMessage, networkDelivery, NetworkManager.ServerClientId); + m_CachedNetworkManager.MessageManager.SendMessage(ref m_OutboundMessage, networkDelivery, NetworkManager.ServerClientId); } m_LocalAuthoritativeNetworkState.LastSerializedSize = m_OutboundMessage.BytesWritten; } @@ -4783,7 +4783,7 @@ public NetworkTransformTickRegistration(NetworkManager networkManager) internal void RegisterForTickSynchronization() { s_TickSynchPosition++; - m_NextTickSync = NetworkManager.ServerTime.Tick + (s_TickSynchPosition % (int)NetworkManager.NetworkConfig.TickRate); + m_NextTickSync = m_CachedNetworkManager.ServerTime.Tick + (s_TickSynchPosition % (int)NetworkManager.NetworkConfig.TickRate); } private static void RegisterNetworkManagerForTickUpdate(NetworkManager networkManager) diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index 9910668f59..4368c1e972 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -574,7 +574,7 @@ public NetworkObject NetworkObject { get { - if (m_NetworkObject != null) + if (m_NetworkObject) { return m_NetworkObject; } @@ -594,7 +594,7 @@ public NetworkObject NetworkObject // or NetworkBehaviour.IsSpawned (i.e. to early exit if not spawned) which, in turn, could generate several Warning messages // per spawned NetworkObject. Checking for ShutdownInProgress prevents these unnecessary LogWarning messages. // We must check IsSpawned, otherwise a warning will be logged under certain valid conditions (see OnDestroy) - if (IsSpawned && m_NetworkObject == null && (m_NetworkManager == null || !m_NetworkManager.ShutdownInProgress)) + if (IsSpawned && !m_NetworkObject && (!m_NetworkManager || !m_NetworkManager.ShutdownInProgress)) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs index 311a3df650..2a7844096e 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs @@ -52,13 +52,7 @@ public sealed class NetworkObject : MonoBehaviour /// Gets the Prefab Hash Id of this object if the object is registerd as a prefab otherwise it returns 0 /// [HideInInspector] - public uint PrefabIdHash - { - get - { - return GlobalObjectIdHash; - } - } + public uint PrefabIdHash => GlobalObjectIdHash; /// /// InstantiationData sent during the instantiation process. @@ -340,26 +334,26 @@ private void CheckForInScenePlaced() internal bool HasParentNetworkObject(Transform transform) { - if (transform.parent != null) + if (m_CachedParent != null) { - var networkObject = transform.parent.GetComponent(); + var networkObject = m_CachedParent.GetComponent(); if (networkObject != null && networkObject != this) { return true; } - if (transform.parent.parent != null) + if (m_CachedParent.parent != null) { - return HasParentNetworkObject(transform.parent); + return HasParentNetworkObject(m_CachedParent); } } return false; } /// - /// Gets the NetworkManager that owns this NetworkObject instance + /// Gets the NetworkManager that owns this NetworkObject instance. /// - public NetworkManager NetworkManager => NetworkManagerOwner ? NetworkManagerOwner : NetworkManager.Singleton; + public NetworkManager NetworkManager = NetworkManager.Singleton; /// /// Useful to know if we should or should not send a message @@ -1114,14 +1108,17 @@ public bool HasOwnershipStatus(OwnershipStatus status) [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool InternalHasAuthority() { - var networkManager = NetworkManager; - return networkManager.DistributedAuthorityMode ? OwnerClientId == networkManager.LocalClientId : networkManager.IsServer; + if (!IsSpawned) + { + return false; + } + return NetworkManagerOwner.DistributedAuthorityMode ? OwnerClientId == NetworkManagerOwner.LocalClientId : NetworkManagerOwner.IsServer; } /// /// The NetworkManager that owns this NetworkObject. /// This property controls where this NetworkObject belongs. - /// This property is null by default currently, which means that the above NetworkManager getter will return the Singleton. + /// This property is null by default currently. /// In the future this is the path where alternative NetworkManagers should be injected for running multi NetworkManagers /// internal NetworkManager NetworkManagerOwner; @@ -1166,17 +1163,17 @@ private bool InternalHasAuthority() /// /// Gets if the object is the personal clients player object /// - public bool IsLocalPlayer => NetworkManager != null && IsPlayerObject && OwnerClientId == NetworkManager.LocalClientId; + public bool IsLocalPlayer => IsPlayerObject && OwnerClientId == NetworkManager.LocalClientId; /// /// Gets if the object is owned by the local player or if the object is the local player object /// - public bool IsOwner => NetworkManager != null && OwnerClientId == NetworkManager.LocalClientId; + public bool IsOwner => OwnerClientId == NetworkManager.LocalClientId; /// /// Gets Whether or not the object is owned by anyone /// - public bool IsOwnedByServer => NetworkManager != null && OwnerClientId == NetworkManager.ServerClientId; + public bool IsOwnedByServer => OwnerClientId == NetworkManager.ServerClientId; /// /// Gets if the object has yet been spawned across the network @@ -2160,11 +2157,11 @@ internal void SetNetworkParenting(ulong? latestParent, bool worldPositionStays) /// /// The new parent for this NetworkObject transform will be the child of. /// If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before. - /// Whether or not reparenting was successful. + /// Whether or not re-parenting was successful. public bool TrySetParent(Transform parent, bool worldPositionStays = true) { // If we are removing ourself from a parent - if (parent == null) + if (!parent) { return TrySetParent((NetworkObject)null, worldPositionStays); } @@ -2180,7 +2177,7 @@ public bool TrySetParent(Transform parent, bool worldPositionStays = true) /// /// The new parent for this NetworkObject transform will be the child of. /// If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before. - /// Whether or not reparenting was successful. + /// Whether or not re-parenting was successful. public bool TrySetParent(GameObject parent, bool worldPositionStays = true) { // If we are removing ourself from a parent @@ -2221,7 +2218,7 @@ public bool TryRemoveParent(bool worldPositionStays = true) /// /// The new parent for this NetworkObject transform will be the child of. /// If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before. - /// Whether or not reparenting was successful. + /// Whether or not re-parenting was successful. public bool TrySetParent(NetworkObject parent, bool worldPositionStays = true) { if (!AutoObjectParentSync) @@ -2229,7 +2226,7 @@ public bool TrySetParent(NetworkObject parent, bool worldPositionStays = true) return false; } - if (NetworkManager == null || !NetworkManager.IsListening) + if (!NetworkManager.IsListening) { return false; } @@ -2238,7 +2235,7 @@ public bool TrySetParent(NetworkObject parent, bool worldPositionStays = true) // It wouldn't make sense to not allow parenting, but keeping this note here as a reminder. 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 (!isAuthority && !NetworkManager.ShutdownInProgress) { @@ -2250,7 +2247,7 @@ public bool TrySetParent(NetworkObject parent, bool worldPositionStays = true) internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays = true) { - if (parent != null && (IsSpawned ^ parent.IsSpawned) && NetworkManager != null && !NetworkManager.ShutdownInProgress) + if (!parent && (IsSpawned ^ parent.IsSpawned) && !NetworkManager.ShutdownInProgress) { if (NetworkManager.LogLevel <= LogLevel.Developer) { @@ -2262,7 +2259,7 @@ internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays m_CachedWorldPositionStays = worldPositionStays; - if (parent == null) + if (!parent) { CurrentParent = null; transform.SetParent(null, worldPositionStays); @@ -2288,7 +2285,7 @@ private void OnTransformParentChanged() return; } - if (NetworkManager == null || !NetworkManager.IsListening) + if (!NetworkManager.IsListening) { // DANGO-TODO: Review as to whether we want to provide a better way to handle changing parenting of objects when the // object is not spawned. Really, we shouldn't care about these types of changes. @@ -2298,7 +2295,7 @@ private void OnTransformParentChanged() return; } transform.parent = m_CachedParent; - Debug.LogException(new NotListeningException($"{nameof(NetworkManager)} is not listening, start a server or host before reparenting")); + Debug.LogException(new NotListeningException($"{nameof(NetworkManager)} is not listening, start a server or host before re-parenting")); return; } var isAuthority = false; @@ -2310,18 +2307,17 @@ private void OnTransformParentChanged() // If we do not have authority and we are spawned if (!isAuthority && IsSpawned) { - - // If the cached parent has not already been set and we are in distributed authority mode, then log an exception and exit early as a non-authority instance + // If the cached parent has not already been set, and we are in distributed authority mode, then log an exception and exit early as a non-authority instance // is trying to set the parent. if (distributedAuthority) { transform.parent = m_CachedParent; - NetworkLog.LogError($"[Not Owner] Only the owner-authority of child {gameObject.name}'s {nameof(NetworkObject)} component can reparent it!"); + NetworkLog.LogError($"[Not Owner] Only the owner-authority of child {gameObject.name}'s {nameof(NetworkObject)} component can re-parent it!"); } else { transform.parent = m_CachedParent; - Debug.LogException(new NotServerException($"Only the server can reparent {nameof(NetworkObject)}s")); + Debug.LogException(new NotServerException($"Only the server can re-parent {nameof(NetworkObject)}s")); } return; } @@ -2339,16 +2335,15 @@ private void OnTransformParentChanged() else { transform.parent = m_CachedParent; - Debug.LogException(new SpawnStateException($"{nameof(NetworkObject)} can only be reparented after being spawned")); + Debug.LogException(new SpawnStateException($"{nameof(NetworkObject)} can only be re-parented after being spawned")); } return; } var removeParent = false; var parentTransform = transform.parent; - var parentObject = (NetworkObject)null; if (parentTransform != null) { - if (!transform.parent.TryGetComponent(out parentObject)) + if (!transform.parent.TryGetComponent(out NetworkObject parentObject)) { transform.parent = m_CachedParent; AuthorityAppliedParenting = false; @@ -2359,7 +2354,7 @@ private void OnTransformParentChanged() { transform.parent = m_CachedParent; AuthorityAppliedParenting = false; - Debug.LogException(new SpawnStateException($"{nameof(NetworkObject)} can only be reparented under another spawned {nameof(NetworkObject)}")); + Debug.LogException(new SpawnStateException($"{nameof(NetworkObject)} can only be re-parented under another spawned {nameof(NetworkObject)}")); return; } @@ -2378,7 +2373,7 @@ private void OnTransformParentChanged() var message = new ParentSyncMessage { NetworkObjectId = NetworkObjectId, - IsLatestParentSet = m_LatestParent != null && m_LatestParent.HasValue, + IsLatestParentSet = m_LatestParent is not null, LatestParent = m_LatestParent, RemoveParent = removeParent, AuthorityApplied = authorityApplied, @@ -2455,15 +2450,15 @@ internal bool ApplyNetworkParenting(bool removeParent = false, bool ignoreNotSpa // has been set, this will not be entered into again (i.e. the later code will be invoked and // users will get notifications when the parent changes). var isInScenePlaced = IsSceneObject.HasValue && IsSceneObject.Value; - if (transform.parent != null && !removeParent && !m_LatestParent.HasValue && isInScenePlaced) + if (!transform.parent && !removeParent && !m_LatestParent.HasValue && isInScenePlaced) { var parentNetworkObject = transform.parent.GetComponent(); // If parentNetworkObject is null then the parent is a GameObject without a NetworkObject component - // attached. Under this case, we preserve the hierarchy but we don't keep track of the parenting. + // attached. Under this case, we preserve the hierarchy, but we don't keep track of the parenting. // Note: We only start tracking parenting if the user removes the child from the standard GameObject // parent and then re-parents the child under a GameObject with a NetworkObject component attached. - if (parentNetworkObject == null) + if (!parentNetworkObject) { // If we are parented under a GameObject, go ahead and mark the world position stays as false // so clients synchronize their transform in local space. (only for in-scene placed NetworkObjects) @@ -2479,7 +2474,7 @@ internal bool ApplyNetworkParenting(bool removeParent = false, bool ignoreNotSpa else { // If we made it this far, go ahead and set the network parenting values - // with the WorldPoisitonSays value set to false + // with the WorldPositionSays value set to false. // Note: Since in-scene placed NetworkObjects are parented in the scene // the default "assumption" is that children are parenting local space // relative. @@ -2492,7 +2487,7 @@ internal bool ApplyNetworkParenting(bool removeParent = false, bool ignoreNotSpa } } - // If we are removing the parent or our latest parent is not set, then remove the parent + // If we are removing the parent or our latest parent is not set, then remove the parent. // removeParent is only set when: // - The server-side NetworkObject.OnTransformParentChanged is invoked and the parent is being removed // - The client-side when handling a ParentSyncMessage @@ -3173,7 +3168,7 @@ internal SceneObject GetMessageSceneObject(ulong targetClientId = NetworkManager { var obj = new SceneObject { - HasParent = transform.parent != null, + HasParent = m_CachedParent is not null, WorldPositionStays = m_CachedWorldPositionStays, NetworkObjectId = NetworkObjectId, OwnerClientId = OwnerClientId, @@ -3195,7 +3190,7 @@ internal SceneObject GetMessageSceneObject(ulong targetClientId = NetworkManager // Handle Parenting if (!AlwaysReplicateAsRoot && obj.HasParent) { - var parentNetworkObject = transform.parent.GetComponent(); + var parentNetworkObject = m_CachedParent.GetComponent(); if (parentNetworkObject) { @@ -3418,9 +3413,9 @@ internal void SubscribeToActiveSceneForSynch() /// private void CurrentlyActiveSceneChanged(Scene current, Scene next) { - // Early exit if there is no NetworkManager assigned, the NetworkManager is shutting down, the NetworkObject + // Early exit if the NetworkManager is shutting down, the NetworkObject // is not spawned, or an in-scene placed NetworkObject - if (NetworkManager == null || NetworkManager.ShutdownInProgress || !IsSpawned || IsSceneObject != false) + if (NetworkManager.ShutdownInProgress || !IsSpawned || IsSceneObject != false) { return; } @@ -3430,7 +3425,7 @@ private void CurrentlyActiveSceneChanged(Scene current, Scene next) { // Only dynamically spawned NetworkObjects that are not already in the newly assigned active scene will migrate // and update their scene handles - if (IsSceneObject.HasValue && !IsSceneObject.Value && gameObject.scene != next && gameObject.transform.parent == null) + if (IsSceneObject.HasValue && !IsSceneObject.Value && m_SceneOrigin != next && m_CachedParent == null) { SceneManager.MoveGameObjectToScene(gameObject, next); SceneChangedUpdate(next); @@ -3489,7 +3484,7 @@ internal void SceneChangedUpdate(Scene scene, bool notify = false) OnMigratedToNewScene?.Invoke(); // Only the authority side will notify clients of non-parented NetworkObject scene changes - if (isAuthority && notify && transform.parent == null) + if (isAuthority && notify && !m_CachedParent) { NetworkManager.SceneManager.NotifyNetworkObjectSceneChanged(this); } @@ -3519,10 +3514,10 @@ private void Awake() /// internal bool UpdateForSceneChanges() { - // Early exit if SceneMigrationSynchronization is disabled, there is no NetworkManager assigned, + // Early exit if SceneMigrationSynchronization is disabled, // the NetworkManager is shutting down, the NetworkObject is not spawned, it is an in-scene placed // NetworkObject, or the GameObject's current scene handle is the same as the SceneOriginHandle - if (!SceneMigrationSynchronization || !IsSpawned || NetworkManager == null || NetworkManager.ShutdownInProgress || + if (!SceneMigrationSynchronization || !IsSpawned || NetworkManager.ShutdownInProgress || !NetworkManager.NetworkConfig.EnableSceneManagement || IsSceneObject != false || !gameObject) { // Stop checking for a scene migration