Skip to content

Commit a31fee7

Browse files
refactor: Remove unnecessary exceptions and refactor logging on NetworkSpawnManager and NetworkObject (#3933)
Refactor logging: - Replace exceptions with log-based error handling - Replace Debug with NetworkLog - Move return calls outside log-level checks Tests: - Fix failures when running in sequence (NetworkManager singleton not updated) - Update tests to expect logs instead of exceptions - Add Netcode prefix to expected logs Cleanup: - Remove unreachable code, redundant branches, and unused comments - General formatting and code cleanup - Update changelog - Address review feedback
1 parent 296b9f5 commit a31fee7

File tree

6 files changed

+200
-130
lines changed

6 files changed

+200
-130
lines changed

com.unity.netcode.gameobjects/CHANGELOG.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,18 @@ Additional documentation and release notes are available at [Multiplayer Documen
1313

1414
### Changed
1515

16-
- Improve performance of `NetworkBehaviour`. (#3915)
17-
- Improve performance of `NetworkTransform`. (#3907)
18-
- Improve performance of `NetworkRigidbodyBase`. (#3906)
19-
- Improve performance of `NetworkAnimator`. (#3905)
16+
- Replaced Debug usage by NetcodeLog on `NetworkSpawnManager` and `NetworkObject`. (#3933)
17+
- Improved performance of `NetworkBehaviour`. (#3915)
18+
- Improved performance of `NetworkTransform`. (#3907)
19+
- Improved performance of `NetworkRigidbodyBase`. (#3906)
20+
- Improved performance of `NetworkAnimator`. (#3905)
2021

2122
### Deprecated
2223

2324

2425
### Removed
2526

27+
- Removed un-needed exceptions on `NetworkSpawnManager`. (#3933)
2628

2729
### Fixed
2830

com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs

Lines changed: 58 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,7 @@ internal void OnValidate()
297297
if (globalId.identifierType != k_SceneObjectType)
298298
{
299299
// This should never happen, but in the event it does throw and error.
300-
Debug.LogError($"[{gameObject.name}] is detected as an in-scene placed object but its identifier is of type {globalId.identifierType}! **Report this error**");
300+
NetworkLog.LogError($"[{gameObject.name}] is detected as an in-scene placed object but its identifier is of type {globalId.identifierType}! **Report this error**");
301301
}
302302

303303
// If this is a prefab instance, then we want to mark it as having been updated in order for the udpated GlobalObjectIdHash value to be saved.
@@ -1762,23 +1762,25 @@ internal void SpawnInternal(bool destroyWithScene, ulong ownerClientId, bool pla
17621762
{
17631763
NetworkLog.LogError($"[{name}] When distributed authority mode is enabled, you can only spawn NetworkObjects that belong to the local instance! Local instance id {NetworkManagerOwner.LocalClientId} is not the same as the assigned owner id: {ownerClientId}!");
17641764
}
1765-
return;
17661765
}
17671766
else
17681767
{
17691768
if (NetworkManagerOwner.LogLevel <= LogLevel.Error)
17701769
{
17711770
NetworkLog.LogError($"[{name}] Only server can spawn {nameof(NetworkObject)}s.");
17721771
}
1773-
return;
17741772
}
1773+
return;
17751774
}
17761775

17771776
if (NetworkManagerOwner.DistributedAuthorityMode)
17781777
{
17791778
if (NetworkManagerOwner.LocalClient == null || !NetworkManagerOwner.IsConnectedClient || !NetworkManagerOwner.ConnectionManager.LocalClient.IsApproved)
17801779
{
1781-
Debug.LogError($"Cannot spawn {name} until the client is fully connected to the session!");
1780+
if (NetworkManagerOwner.LogLevel <= LogLevel.Error)
1781+
{
1782+
NetworkLog.LogError($"Cannot spawn {name} until the client is fully connected to the session!");
1783+
}
17821784
return;
17831785
}
17841786
if (NetworkManagerOwner.NetworkConfig.EnableSceneManagement)
@@ -1834,7 +1836,10 @@ internal void SpawnInternal(bool destroyWithScene, ulong ownerClientId, bool pla
18341836
}
18351837
else
18361838
{
1837-
NetworkLog.LogWarningServer($"[{name}] Ran into unknown conditional check during spawn when determining distributed authority mode or not");
1839+
if (NetworkManagerOwner.LogLevel <= LogLevel.Normal)
1840+
{
1841+
NetworkLog.LogWarningServer($"[{name}] Ran into unknown conditional check during spawn when determining distributed authority mode or not");
1842+
}
18381843
}
18391844
}
18401845

@@ -1856,7 +1861,10 @@ public static NetworkObject InstantiateAndSpawn(GameObject networkPrefab, Networ
18561861
var networkObject = networkPrefab.GetComponent<NetworkObject>();
18571862
if (networkObject == null)
18581863
{
1859-
Debug.LogError($"The {nameof(NetworkPrefab)} {networkPrefab.name} does not have a {nameof(NetworkObject)} component!");
1864+
if (networkManager.LogLevel <= LogLevel.Error)
1865+
{
1866+
NetworkLog.LogError($"The {nameof(NetworkPrefab)} {networkPrefab.name} does not have a {nameof(NetworkObject)} component!");
1867+
}
18601868
return null;
18611869
}
18621870
return networkObject.InstantiateAndSpawn(networkManager, ownerClientId, destroyWithScene, isPlayerObject, forceOverride, position, rotation);
@@ -1878,34 +1886,49 @@ public NetworkObject InstantiateAndSpawn(NetworkManager networkManager, ulong ow
18781886
{
18791887
if (networkManager == null)
18801888
{
1881-
Debug.LogError(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.NetworkManagerNull]);
1889+
if (NetworkManager.LogLevel <= LogLevel.Error)
1890+
{
1891+
NetworkLog.LogError(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.NetworkManagerNull]);
1892+
}
18821893
return null;
18831894
}
18841895

18851896
if (!networkManager.IsListening)
18861897
{
1887-
Debug.LogError(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.NoActiveSession]);
1898+
if (networkManager.LogLevel <= LogLevel.Error)
1899+
{
1900+
NetworkLog.LogError(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.NoActiveSession]);
1901+
}
18881902
return null;
18891903
}
18901904

18911905
ownerClientId = networkManager.DistributedAuthorityMode ? networkManager.LocalClientId : ownerClientId;
18921906
// We only need to check for authority when running in client-server mode
18931907
if (!networkManager.IsServer && !networkManager.DistributedAuthorityMode)
18941908
{
1895-
Debug.LogError(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.NotAuthority]);
1909+
if (networkManager.LogLevel <= LogLevel.Error)
1910+
{
1911+
NetworkLog.LogError(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.NotAuthority]);
1912+
}
18961913
return null;
18971914
}
18981915

18991916
if (networkManager.ShutdownInProgress)
19001917
{
1901-
Debug.LogWarning(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.InvokedWhenShuttingDown]);
1918+
if (networkManager.LogLevel <= LogLevel.Normal)
1919+
{
1920+
NetworkLog.LogWarning(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.InvokedWhenShuttingDown]);
1921+
}
19021922
return null;
19031923
}
19041924

19051925
// Verify it is actually a valid prefab
19061926
if (!networkManager.NetworkConfig.Prefabs.Contains(gameObject))
19071927
{
1908-
Debug.LogError(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.NotRegisteredNetworkPrefab]);
1928+
if (networkManager.LogLevel <= LogLevel.Error)
1929+
{
1930+
NetworkLog.LogError(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.NotRegisteredNetworkPrefab]);
1931+
}
19091932
return null;
19101933
}
19111934

@@ -1961,7 +1984,6 @@ public void Despawn(bool destroy = true)
19611984
{
19621985
NetworkLog.LogErrorServer($"[{name}][Attempted despawn before {nameof(NetworkObject)} was spawned]");
19631986
}
1964-
19651987
return;
19661988
}
19671989

@@ -2011,10 +2033,8 @@ public void ChangeOwnership(ulong newOwnerClientId)
20112033
{
20122034
NetworkLog.LogErrorServer($"[{name}][Attempted ownership change before {nameof(NetworkObject)} was spawned]");
20132035
}
2014-
20152036
return;
20162037
}
2017-
20182038
NetworkManagerOwner.SpawnManager.ChangeOwnership(this, newOwnerClientId, HasAuthority);
20192039
}
20202040

@@ -2030,7 +2050,6 @@ internal void InvokeBehaviourOnOwnershipChanged(ulong originalOwnerClientId, ulo
20302050
{
20312051
NetworkLog.LogErrorServer($"[{name}][Attempted behavior invoke on ownership changed before {nameof(NetworkObject)} was spawned]");
20322052
}
2033-
20342053
return;
20352054
}
20362055

@@ -2061,10 +2080,12 @@ internal void InvokeBehaviourOnOwnershipChanged(ulong originalOwnerClientId, ulo
20612080
{
20622081
if (!childBehaviour.gameObject.activeInHierarchy)
20632082
{
2064-
Debug.LogWarning($"[{name}] {childBehaviour.gameObject.name} is disabled! Netcode for GameObjects does not support disabled NetworkBehaviours! The {childBehaviour.GetType().Name} component was skipped during ownership assignment!");
2083+
if (NetworkManagerOwner.LogLevel <= LogLevel.Normal)
2084+
{
2085+
NetworkLog.LogWarning($"[{name}] {childBehaviour.gameObject.name} is disabled! Netcode for GameObjects does not support disabled NetworkBehaviours! The {childBehaviour.GetType().Name} component was skipped during ownership assignment!");
2086+
}
20652087
continue;
20662088
}
2067-
20682089
childBehaviour.InternalOnGainedOwnership();
20692090
}
20702091
}
@@ -2080,7 +2101,10 @@ internal void InvokeOwnershipChanged(ulong previous, ulong next)
20802101
}
20812102
else
20822103
{
2083-
Debug.LogWarning($"[{name}] {ChildNetworkBehaviours[i].gameObject.name} is disabled! Netcode for GameObjects does not support disabled NetworkBehaviours! The {ChildNetworkBehaviours[i].GetType().Name} component was skipped during ownership assignment!");
2104+
if (NetworkManagerOwner.LogLevel <= LogLevel.Normal)
2105+
{
2106+
NetworkLog.LogWarning($"[{name}] {ChildNetworkBehaviours[i].gameObject.name} is disabled! Netcode for GameObjects does not support disabled NetworkBehaviours! The {ChildNetworkBehaviours[i].GetType().Name} component was skipped during ownership assignment!");
2107+
}
20842108
}
20852109
}
20862110
}
@@ -2271,7 +2295,7 @@ internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays
22712295
private void OnTransformParentChanged()
22722296
{
22732297
var networkManager = NetworkManager;
2274-
if (!AutoObjectParentSync || networkManager.ShutdownInProgress)
2298+
if (!AutoObjectParentSync || (networkManager != null && networkManager.ShutdownInProgress))
22752299
{
22762300
return;
22772301
}
@@ -2283,18 +2307,9 @@ private void OnTransformParentChanged()
22832307

22842308
if (networkManager == null || !networkManager.IsListening)
22852309
{
2286-
// DANGO-TODO: Review as to whether we want to provide a better way to handle changing parenting of objects when the
2287-
// object is not spawned. Really, we shouldn't care about these types of changes.
2288-
if (networkManager.DistributedAuthorityMode && m_CachedParent != null && transform.parent == null)
2289-
{
2290-
m_CachedParent = null;
2291-
return;
2292-
}
22932310
transform.parent = m_CachedParent;
2294-
if (NetworkManagerOwner.LogLevel <= LogLevel.Error)
2295-
{
2296-
NetworkLog.LogError($"[{name}] {nameof(networkManager)} is not listening, start a server or host before re-parenting.");
2297-
}
2311+
// We want to log at any LogLevel, since we may not have a network manager may here.
2312+
NetworkLog.LogError($"[{name}] {nameof(networkManager)} is not listening, start a server or host before re-parenting.");
22982313
return;
22992314
}
23002315

@@ -2311,7 +2326,7 @@ private void OnTransformParentChanged()
23112326
else
23122327
{
23132328
transform.parent = m_CachedParent;
2314-
if (NetworkManagerOwner.LogLevel <= LogLevel.Error)
2329+
if (networkManager.LogLevel <= LogLevel.Error)
23152330
{
23162331
NetworkLog.LogErrorServer($"[{name}] {nameof(NetworkObject)} can only be re-parented after being spawned!");
23172332
}
@@ -2348,17 +2363,17 @@ private void OnTransformParentChanged()
23482363
{
23492364
transform.parent = m_CachedParent;
23502365
AuthorityAppliedParenting = false;
2351-
if (NetworkManagerOwner.LogLevel <= LogLevel.Error)
2366+
if (networkManager.LogLevel <= LogLevel.Error)
23522367
{
23532368
NetworkLog.LogErrorServer($"[{name}] Invalid parenting, {nameof(NetworkObject)} moved under a non-{nameof(NetworkObject)} parent");
23542369
}
23552370
return;
23562371
}
2357-
else if (!parentObject.IsSpawned)
2372+
if (!parentObject.IsSpawned)
23582373
{
23592374
transform.parent = m_CachedParent;
23602375
AuthorityAppliedParenting = false;
2361-
if (NetworkManagerOwner.LogLevel <= LogLevel.Error)
2376+
if (networkManager.LogLevel <= LogLevel.Error)
23622377
{
23632378
NetworkLog.LogErrorServer($"[{name}] {nameof(NetworkObject)} can only be re-parented under another spawned {nameof(NetworkObject)}.");
23642379
}
@@ -2494,10 +2509,10 @@ internal bool ApplyNetworkParenting(bool removeParent = false, bool ignoreNotSpa
24942509
}
24952510
}
24962511

2497-
// If we are removing the parent or our latest parent is not set, then remove the parent
2512+
// If we are removing the parent or our latest parent is not set, then remove the parent.
24982513
// removeParent is only set when:
24992514
// - The server-side NetworkObject.OnTransformParentChanged is invoked and the parent is being removed
2500-
// - The client-side when handling a ParentSyncMessage
2515+
// - The client-side is handling a ParentSyncMessage
25012516
// When clients are synchronizing only the m_LatestParent.HasValue will not have a value if there is no parent
25022517
// or a parent was removed prior to the client connecting (i.e. in-scene placed NetworkObjects)
25032518
if (removeParent || !m_LatestParent.HasValue)
@@ -2597,7 +2612,10 @@ internal void InvokeBehaviourNetworkSpawn()
25972612
{
25982613
if (!childBehaviour.gameObject.activeInHierarchy)
25992614
{
2600-
Debug.LogWarning($"{GenerateDisabledNetworkBehaviourWarning(childBehaviour)}");
2615+
if (NetworkManager.LogLevel <= LogLevel.Normal)
2616+
{
2617+
NetworkLog.LogWarning($"{GenerateDisabledNetworkBehaviourWarning(childBehaviour)}");
2618+
}
26012619
continue;
26022620
}
26032621
childBehaviour.NetworkSpawn();
@@ -2709,7 +2727,6 @@ internal List<NetworkBehaviour> ChildNetworkBehaviours
27092727
}
27102728
#endif
27112729
}
2712-
27132730
return m_ChildNetworkBehaviours;
27142731
}
27152732
}
@@ -2876,9 +2893,7 @@ internal struct SerializedObject
28762893
public bool HasParent;
28772894
public bool IsSceneObject;
28782895
public bool HasTransform;
2879-
28802896
public bool IsLatestParentSet;
2881-
28822897
public bool WorldPositionStays;
28832898

28842899
/// <summary>
@@ -2888,15 +2903,10 @@ internal struct SerializedObject
28882903
/// to the current active scene when its scene is unloaded. (only for dynamically spawned)
28892904
/// </summary>
28902905
public bool DestroyWithScene;
2891-
28922906
public bool DontDestroyWithOwner;
2893-
28942907
public bool HasOwnershipFlags;
2895-
28962908
public bool SyncObservers;
2897-
28982909
public bool SpawnWithObservers;
2899-
29002910
public bool HasInstantiationData;
29012911

29022912
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -2988,9 +2998,6 @@ public struct TransformData : INetworkSerializeByMemcpy
29882998

29892999
public TransformData Transform;
29903000

2991-
//If(Metadata.IsReparented)
2992-
2993-
//If(IsLatestParentSet)
29943001
public ulong? LatestParent;
29953002

29963003
public NetworkObject OwnerObject;
@@ -3310,11 +3317,8 @@ internal static NetworkObject Deserialize(in SerializedObject serializedObject,
33103317
reader.ReadValueSafe(out instantiationData);
33113318
}
33123319

3313-
33143320
// Attempt to create a local NetworkObject
33153321
var networkObject = networkManager.SpawnManager.CreateLocalNetworkObject(serializedObject, instantiationData);
3316-
3317-
33183322
if (networkObject == null)
33193323
{
33203324
// Log the error that the NetworkObject failed to construct
@@ -3336,7 +3340,6 @@ internal static NetworkObject Deserialize(in SerializedObject serializedObject,
33363340
// We have nothing left to do here.
33373341
return null;
33383342
}
3339-
33403343
networkObject.NetworkManagerOwner = networkManager;
33413344

33423345
// This will get set again when the NetworkObject is spawned locally, but we set it here ahead of spawning
@@ -3625,17 +3628,13 @@ internal uint CheckForGlobalObjectIdHashOverride()
36253628
{
36263629
return PrefabGlobalObjectIdHash;
36273630
}
3628-
else
3631+
// For legacy manual instantiation and spawning, check the OverrideToNetworkPrefab for a possible match
3632+
if (networkManager.NetworkConfig.Prefabs.OverrideToNetworkPrefab.TryGetValue(GlobalObjectIdHash, out var overrideHash))
36293633
{
3630-
// For legacy manual instantiation and spawning, check the OverrideToNetworkPrefab for a possible match
3631-
if (networkManager.NetworkConfig.Prefabs.OverrideToNetworkPrefab.ContainsKey(GlobalObjectIdHash))
3632-
{
3633-
return networkManager.NetworkConfig.Prefabs.OverrideToNetworkPrefab[GlobalObjectIdHash];
3634-
}
3634+
return overrideHash;
36353635
}
36363636
}
36373637
}
3638-
36393638
return GlobalObjectIdHash;
36403639
}
36413640

0 commit comments

Comments
 (0)