Skip to content

Commit be8a02a

Browse files
feat: add pre and post spawn methods [MTT-8470] up-port v2.0.0 (#2912)
* update adding pre and post spawn methods. clearing the m_ChildNetworkBehaviours on Awake. * update adding change log entries * update Needed to add a NetworkManager ref into the pre spawn method. Needed to account for locally spawning. * test Adding test that validates the pre spawn and post spawn methods are invoked and that order of operations for OnNetworkSpawn invocation is not an issue with OnNetworkPostSpawn invocation. * style updating comments * style updating comments a bit more * test Migrating OnDynamicNetworkPreAndPostSpawn into its own class to avoid interfering with the generic tests. * style removing property no longer used and remove LF/CR * update and test Added NetworkBehaviour.OnNetworkSessionSynchronized and NetworkBehaviour.OnInSceneObjectsSpawned methods. Added test to validate the above methods. Added assets for the test to validate the above methods. * update Merge fix * test Updates for distributed authority testing. * Update CHANGELOG.md Adding v2.0.0 PR * style removing white spaces
1 parent db2315c commit be8a02a

16 files changed

Lines changed: 814 additions & 3 deletions

com.unity.netcode.gameobjects/CHANGELOG.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,13 @@ Additional documentation and release notes are available at [Multiplayer Documen
1010

1111
### Added
1212

13+
- Added `NetworkBehaviour.OnNetworkPreSpawn` and `NetworkBehaviour.OnNetworkPostSpawn` methods that provide the ability to handle pre and post spawning actions during the `NetworkObject` spawn sequence. (#2912)
14+
- Added a client-side only `NetworkBehaviour.OnNetworkSessionSynchronized` convenience method that is invoked on all `NetworkBehaviour`s after a newly joined client has finished synchronizing with the network session in progress. (#2912)
15+
- Added `NetworkBehaviour.OnInSceneObjectsSpawned` convenience method that is invoked when all in-scene `NetworkObject`s have been spawned after a scene has been loaded or upon a host or server starting. (#2912)
16+
1317
### Fixed
1418

19+
- Fixed issue where a `NetworkObject` component's associated `NetworkBehaviour` components would not be detected if scene loading is disabled in the editor and the currently loaded scene has in-scene placed `NetworkObject`s. (#2912)
1520
- Fixed issue where an in-scene placed `NetworkObject` with `NetworkTransform` that is also parented under a `GameObject` would not properly synchronize when the parent `GameObject` had a world space position other than 0,0,0. (#2898)
1621

1722
### Changed
@@ -63,7 +68,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
6368
- Added distributed authority mode specific `NetworkObject.OnDeferredDespawnComplete` callback handler that can be used to further control when deferring the despawning of a `NetworkObject` on non-authoritative instances. (#2863)
6469
- Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863)
6570
- Added distributed authority mode specific `NetworkClient.IsSessionOwner` property to determine if the current local client is the current session owner of a distributed authority session. (#2863)
66-
- Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is authomatically the owner of the spawned object). (#2863)
71+
- Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is automatically the owner of the spawned object). (#2863)
6772
- This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example).
6873
- Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863)
6974
- Added distributed authority mode specific `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property (default is true) to provide control over the automatic spawning of player prefabs on the local client side. (#2863)
@@ -90,6 +95,36 @@ Additional documentation and release notes are available at [Multiplayer Documen
9095
- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)
9196
- Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807)
9297

98+
## [1.9.1] - 2024-04-18
99+
100+
### Added
101+
- Added `AnticipatedNetworkVariable<T>`, which adds support for client anticipation of NetworkVariable values, allowing for more responsive game play (#2820)
102+
- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of `NetworkTransform`s (#2820)
103+
- Added `NetworkVariableBase.ExceedsDirtinessThreshold` to allow network variables to throttle updates by only sending updates when the difference between the current and previous values exceeds a threshold. (This is exposed in NetworkVariable<T> with the callback NetworkVariable<T>.CheckExceedsDirtinessThreshold) (#2820)
104+
- Added `NetworkVariableUpdateTraits`, which add additional throttling support: `MinSecondsBetweenUpdates` will prevent the `NetworkVariable` from sending updates more often than the specified time period (even if it exceeds the dirtiness threshold), while `MaxSecondsBetweenUpdates` will force a dirty `NetworkVariable` to send an update after the specified time period even if it has not yet exceeded the dirtiness threshold. (#2820)
105+
- Added virtual method `NetworkVariableBase.OnInitialize()` which can be used by `NetworkVariable` subclasses to add initialization code (#2820)
106+
- Added virtual method `NetworkVariableBase.Update()`, which is called once per frame to support behaviors such as interpolation between an anticipated value and an authoritative one. (#2820)
107+
- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2820)
108+
- `NetworkVariable` now includes built-in support for `NativeHashSet`, `NativeHashMap`, `List`, `HashSet`, and `Dictionary` (#2813)
109+
- `NetworkVariable` now includes delta compression for collection values (`NativeList`, `NativeArray`, `NativeHashSet`, `NativeHashMap`, `List`, `HashSet`, `Dictionary`, and `FixedString` types) to save bandwidth by only sending the values that changed. (Note: For `NativeList`, `NativeArray`, and `List`, this algorithm works differently than that used in `NetworkList`. This algorithm will use less bandwidth for "set" and "add" operations, but `NetworkList` is more bandwidth-efficient if you are performing frequent "insert" operations.) (#2813)
110+
- `UserNetworkVariableSerialization` now has optional callbacks for `WriteDelta` and `ReadDelta`. If both are provided, they will be used for all serialization operations on NetworkVariables of that type except for the first one for each client. If either is missing, the existing `Write` and `Read` will always be used. (#2813)
111+
- Network variables wrapping `INetworkSerializable` types can perform delta serialization by setting `UserNetworkVariableSerialization<T>.WriteDelta` and `UserNetworkVariableSerialization<T>.ReadDelta` for those types. The built-in `INetworkSerializable` serializer will continue to be used for all other serialization operations, but if those callbacks are set, it will call into them on all but the initial serialization to perform delta serialization. (This could be useful if you have a large struct where most values do not change regularly and you want to send only the fields that did change.) (#2813)
112+
113+
### Fixed
114+
115+
- Fixed issue where `NetworkTransformEditor` would throw and exception if you excluded the physics package. (#2871)
116+
- Fixed issue where `NetworkTransform` could not properly synchronize its base position when using half float precision. (#2845)
117+
- Fixed issue where the host was not invoking `OnClientDisconnectCallback` for its own local client when internally shutting down. (#2822)
118+
- Fixed issue where NetworkTransform could potentially attempt to "unregister" a named message prior to it being registered. (#2807)
119+
- Fixed issue where in-scene placed `NetworkObject`s with complex nested children `NetworkObject`s (more than one child in depth) would not synchronize properly if WorldPositionStays was set to true. (#2796)
120+
121+
### Changed
122+
123+
- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2874)
124+
- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2872)
125+
- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)
126+
- Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807)
127+
93128
## [1.8.1] - 2024-02-05
94129

95130
### Fixed

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

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -660,16 +660,69 @@ internal void UpdateNetworkProperties()
660660
/// <param name="despawnTick">the future network tick that the <see cref="NetworkObject"/> will be despawned on non-authoritative instances</param>
661661
public virtual void OnDeferringDespawn(int despawnTick) { }
662662

663+
/// Gets called after the <see cref="NetworkObject"/> is spawned. No NetworkBehaviours associated with the NetworkObject will have had <see cref="OnNetworkSpawn"/> invoked yet.
664+
/// A reference to <see cref="NetworkManager"/> is passed in as a parameter to determine the context of execution (IsServer/IsClient)
665+
/// </summary>
666+
/// <remarks>
667+
/// <param name="networkManager">a ref to the <see cref="NetworkManager"/> since this is not yet set on the <see cref="NetworkBehaviour"/></param>
668+
/// The <see cref="NetworkBehaviour"/> will not have anything assigned to it at this point in time.
669+
/// Settings like ownership, NetworkBehaviourId, NetworkManager, and most other spawn related properties will not be set.
670+
/// This can be used to handle things like initializing/instantiating a NetworkVariable or the like.
671+
/// </remarks>
672+
protected virtual void OnNetworkPreSpawn(ref NetworkManager networkManager) { }
673+
663674
/// <summary>
664675
/// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered and the network is setup.
665676
/// </summary>
666677
public virtual void OnNetworkSpawn() { }
667678

679+
/// <summary>
680+
/// Gets called after the <see cref="NetworkObject"/> is spawned. All NetworkBehaviours associated with the NetworkObject will have had <see cref="OnNetworkSpawn"/> invoked.
681+
/// </summary>
682+
/// <remarks>
683+
/// Will be invoked on each <see cref="NetworkBehaviour"/> associated with the <see cref="NetworkObject"/> being spawned.
684+
/// All associated <see cref="NetworkBehaviour"/> components will have had <see cref="OnNetworkSpawn"/> invoked on the spawned <see cref="NetworkObject"/>.
685+
/// </remarks>
686+
protected virtual void OnNetworkPostSpawn() { }
687+
688+
/// <summary>
689+
/// [Client-Side Only]
690+
/// When a new client joins it is synchronized with all spawned NetworkObjects and scenes loaded for the session joined. At the end of the synchronization process, when all
691+
/// <see cref="NetworkObject"/>s and scenes (if scene management is enabled) have finished synchronizing, all NetworkBehaviour components associated with spawned <see cref="NetworkObject"/>s
692+
/// will have this method invoked.
693+
/// </summary>
694+
/// <remarks>
695+
/// This can be used to handle post synchronization actions where you might need to access a different NetworkObject and/or NetworkBehaviour not local to the current NetworkObject context.
696+
/// This is only invoked on clients during a client-server network topology session.
697+
/// </remarks>
698+
protected virtual void OnNetworkSessionSynchronized() { }
699+
700+
/// <summary>
701+
/// [Client & Server Side]
702+
/// When a scene is loaded an in-scene placed NetworkObjects are all spawned, this method is invoked on all of the newly spawned in-scene placed NetworkObjects.
703+
/// </summary>
704+
/// <remarks>
705+
/// This can be used to handle post scene loaded actions for in-scene placed NetworkObjcts where you might need to access a different NetworkObject and/or NetworkBehaviour not local to the current NetworkObject context.
706+
/// </remarks>
707+
protected virtual void OnInSceneObjectsSpawned() { }
708+
668709
/// <summary>
669710
/// Gets called when the <see cref="NetworkObject"/> gets despawned. Is called both on the server and clients.
670711
/// </summary>
671712
public virtual void OnNetworkDespawn() { }
672713

714+
internal void NetworkPreSpawn(ref NetworkManager networkManager)
715+
{
716+
try
717+
{
718+
OnNetworkPreSpawn(ref networkManager);
719+
}
720+
catch (Exception e)
721+
{
722+
Debug.LogException(e);
723+
}
724+
}
725+
673726
internal void InternalOnNetworkSpawn()
674727
{
675728
IsSpawned = true;
@@ -699,6 +752,42 @@ internal void VisibleOnNetworkSpawn()
699752
}
700753
}
701754

755+
internal void NetworkPostSpawn()
756+
{
757+
try
758+
{
759+
OnNetworkPostSpawn();
760+
}
761+
catch (Exception e)
762+
{
763+
Debug.LogException(e);
764+
}
765+
}
766+
767+
internal void NetworkSessionSynchronized()
768+
{
769+
try
770+
{
771+
OnNetworkSessionSynchronized();
772+
}
773+
catch (Exception e)
774+
{
775+
Debug.LogException(e);
776+
}
777+
}
778+
779+
internal void InSceneNetworkObjectsSpawned()
780+
{
781+
try
782+
{
783+
OnInSceneObjectsSpawned();
784+
}
785+
catch (Exception e)
786+
{
787+
Debug.LogException(e);
788+
}
789+
}
790+
702791
internal void InternalOnNetworkDespawn()
703792
{
704793
IsSpawned = false;

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

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2209,6 +2209,18 @@ internal static void CheckOrphanChildren()
22092209
}
22102210
}
22112211

2212+
internal void InvokeBehaviourNetworkPreSpawn()
2213+
{
2214+
var networkManager = NetworkManager;
2215+
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
2216+
{
2217+
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
2218+
{
2219+
ChildNetworkBehaviours[i].NetworkPreSpawn(ref networkManager);
2220+
}
2221+
}
2222+
}
2223+
22122224
internal void InvokeBehaviourNetworkSpawn()
22132225
{
22142226
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId);
@@ -2238,6 +2250,42 @@ internal void InvokeBehaviourNetworkSpawn()
22382250
}
22392251
}
22402252

2253+
internal void InvokeBehaviourNetworkPostSpawn()
2254+
{
2255+
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
2256+
{
2257+
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
2258+
{
2259+
ChildNetworkBehaviours[i].NetworkPostSpawn();
2260+
}
2261+
}
2262+
}
2263+
2264+
2265+
internal void InternalNetworkSessionSynchronized()
2266+
{
2267+
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
2268+
{
2269+
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
2270+
{
2271+
ChildNetworkBehaviours[i].NetworkSessionSynchronized();
2272+
}
2273+
}
2274+
}
2275+
2276+
internal void InternalInSceneNetworkObjectsSpawned()
2277+
{
2278+
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
2279+
{
2280+
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
2281+
{
2282+
ChildNetworkBehaviours[i].InSceneNetworkObjectsSpawned();
2283+
}
2284+
}
2285+
}
2286+
2287+
2288+
22412289
internal void InvokeBehaviourNetworkDespawn()
22422290
{
22432291
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId, true);
@@ -2862,6 +2910,9 @@ internal static NetworkObject AddSceneObject(in SceneObject sceneObject, FastBuf
28622910
// in order to be able to determine which NetworkVariables the client will be allowed to read.
28632911
networkObject.OwnerClientId = sceneObject.OwnerClientId;
28642912

2913+
// Special Case: Invoke NetworkBehaviour.OnPreSpawn methods here before SynchronizeNetworkBehaviours
2914+
networkObject.InvokeBehaviourNetworkPreSpawn();
2915+
28652916
// Synchronize NetworkBehaviours
28662917
var bufferSerializer = new BufferSerializer<BufferSerializerReader>(new BufferSerializerReader(reader));
28672918
networkObject.SynchronizeNetworkBehaviours(ref bufferSerializer, networkManager.LocalClientId);
@@ -3051,6 +3102,7 @@ internal static void UpdateNetworkObjectSceneChanges()
30513102

30523103
private void Awake()
30533104
{
3105+
m_ChildNetworkBehaviours = null;
30543106
SetCachedParent(transform.parent);
30553107
SceneOrigin = gameObject.scene;
30563108
}

com.unity.netcode.gameobjects/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,12 @@ public void Handle(ref NetworkContext context)
222222
}
223223
// When scene management is disabled we notify after everything is synchronized
224224
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId);
225+
226+
// For convenience, notify all NetworkBehaviours that synchronization is complete.
227+
foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList)
228+
{
229+
networkObject.InternalNetworkSessionSynchronized();
230+
}
225231
}
226232
else
227233
{

com.unity.netcode.gameobjects/Runtime/SceneManagement/NetworkSceneManager.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1859,6 +1859,17 @@ private void OnSessionOwnerLoadedScene(uint sceneEventId, Scene scene)
18591859
}
18601860
}
18611861

1862+
foreach (var keyValuePairByGlobalObjectIdHash in ScenePlacedObjects)
1863+
{
1864+
foreach (var keyValuePairBySceneHandle in keyValuePairByGlobalObjectIdHash.Value)
1865+
{
1866+
if (!keyValuePairBySceneHandle.Value.IsPlayerObject)
1867+
{
1868+
keyValuePairBySceneHandle.Value.InternalInSceneNetworkObjectsSpawned();
1869+
}
1870+
}
1871+
}
1872+
18621873
// Add any despawned when spawned in-scene placed NetworkObjects to the scene event data
18631874
sceneEventData.AddDespawnedInSceneNetworkObjects();
18641875

@@ -2413,6 +2424,12 @@ private void HandleClientSceneEvent(uint sceneEventId)
24132424
{
24142425
NetworkLog.LogInfo($"[Client-{NetworkManager.LocalClientId}][Scene Management Enabled] Synchronization complete!");
24152426
}
2427+
// For convenience, notify all NetworkBehaviours that synchronization is complete.
2428+
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
2429+
{
2430+
networkObject.InternalNetworkSessionSynchronized();
2431+
}
2432+
24162433
EndSceneEvent(sceneEventId);
24172434
}
24182435
break;

0 commit comments

Comments
 (0)