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
This commit is contained in:
Noel Stephens 2024-05-01 21:11:49 -05:00 коммит произвёл GitHub
Родитель db2315ce8e
Коммит be8a02a86e
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
16 изменённых файлов: 814 добавлений и 3 удалений

Просмотреть файл

@ -10,8 +10,13 @@ Additional documentation and release notes are available at [Multiplayer Documen
### Added
- Added `NetworkBehaviour.OnNetworkPreSpawn` and `NetworkBehaviour.OnNetworkPostSpawn` methods that provide the ability to handle pre and post spawning actions during the `NetworkObject` spawn sequence. (#2912)
- 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)
- 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)
### Fixed
- 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)
- 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)
### Changed
@ -63,7 +68,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
- 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)
- Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863)
- 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)
- 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)
- 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)
- This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example).
- Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863)
- 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
- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)
- 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)
## [1.9.1] - 2024-04-18
### Added
- Added `AnticipatedNetworkVariable<T>`, which adds support for client anticipation of NetworkVariable values, allowing for more responsive game play (#2820)
- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of `NetworkTransform`s (#2820)
- 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)
- 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)
- Added virtual method `NetworkVariableBase.OnInitialize()` which can be used by `NetworkVariable` subclasses to add initialization code (#2820)
- 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)
- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2820)
- `NetworkVariable` now includes built-in support for `NativeHashSet`, `NativeHashMap`, `List`, `HashSet`, and `Dictionary` (#2813)
- `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)
- `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)
- 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)
### Fixed
- Fixed issue where `NetworkTransformEditor` would throw and exception if you excluded the physics package. (#2871)
- Fixed issue where `NetworkTransform` could not properly synchronize its base position when using half float precision. (#2845)
- Fixed issue where the host was not invoking `OnClientDisconnectCallback` for its own local client when internally shutting down. (#2822)
- Fixed issue where NetworkTransform could potentially attempt to "unregister" a named message prior to it being registered. (#2807)
- 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)
### Changed
- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2874)
- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2872)
- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)
- 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)
## [1.8.1] - 2024-02-05
### Fixed

Просмотреть файл

@ -660,16 +660,69 @@ namespace Unity.Netcode
/// <param name="despawnTick">the future network tick that the <see cref="NetworkObject"/> will be despawned on non-authoritative instances</param>
public virtual void OnDeferringDespawn(int despawnTick) { }
/// Gets called after the <see cref="NetworkObject"/> is spawned. No NetworkBehaviours associated with the NetworkObject will have had <see cref="OnNetworkSpawn"/> invoked yet.
/// A reference to <see cref="NetworkManager"/> is passed in as a parameter to determine the context of execution (IsServer/IsClient)
/// </summary>
/// <remarks>
/// <param name="networkManager">a ref to the <see cref="NetworkManager"/> since this is not yet set on the <see cref="NetworkBehaviour"/></param>
/// The <see cref="NetworkBehaviour"/> will not have anything assigned to it at this point in time.
/// Settings like ownership, NetworkBehaviourId, NetworkManager, and most other spawn related properties will not be set.
/// This can be used to handle things like initializing/instantiating a NetworkVariable or the like.
/// </remarks>
protected virtual void OnNetworkPreSpawn(ref NetworkManager networkManager) { }
/// <summary>
/// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered and the network is setup.
/// </summary>
public virtual void OnNetworkSpawn() { }
/// <summary>
/// Gets called after the <see cref="NetworkObject"/> is spawned. All NetworkBehaviours associated with the NetworkObject will have had <see cref="OnNetworkSpawn"/> invoked.
/// </summary>
/// <remarks>
/// Will be invoked on each <see cref="NetworkBehaviour"/> associated with the <see cref="NetworkObject"/> being spawned.
/// All associated <see cref="NetworkBehaviour"/> components will have had <see cref="OnNetworkSpawn"/> invoked on the spawned <see cref="NetworkObject"/>.
/// </remarks>
protected virtual void OnNetworkPostSpawn() { }
/// <summary>
/// [Client-Side Only]
/// 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
/// <see cref="NetworkObject"/>s and scenes (if scene management is enabled) have finished synchronizing, all NetworkBehaviour components associated with spawned <see cref="NetworkObject"/>s
/// will have this method invoked.
/// </summary>
/// <remarks>
/// 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.
/// This is only invoked on clients during a client-server network topology session.
/// </remarks>
protected virtual void OnNetworkSessionSynchronized() { }
/// <summary>
/// [Client & Server Side]
/// 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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
protected virtual void OnInSceneObjectsSpawned() { }
/// <summary>
/// Gets called when the <see cref="NetworkObject"/> gets despawned. Is called both on the server and clients.
/// </summary>
public virtual void OnNetworkDespawn() { }
internal void NetworkPreSpawn(ref NetworkManager networkManager)
{
try
{
OnNetworkPreSpawn(ref networkManager);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
internal void InternalOnNetworkSpawn()
{
IsSpawned = true;
@ -699,6 +752,42 @@ namespace Unity.Netcode
}
}
internal void NetworkPostSpawn()
{
try
{
OnNetworkPostSpawn();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
internal void NetworkSessionSynchronized()
{
try
{
OnNetworkSessionSynchronized();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
internal void InSceneNetworkObjectsSpawned()
{
try
{
OnInSceneObjectsSpawned();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
internal void InternalOnNetworkDespawn()
{
IsSpawned = false;

Просмотреть файл

@ -2209,6 +2209,18 @@ namespace Unity.Netcode
}
}
internal void InvokeBehaviourNetworkPreSpawn()
{
var networkManager = NetworkManager;
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
{
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
{
ChildNetworkBehaviours[i].NetworkPreSpawn(ref networkManager);
}
}
}
internal void InvokeBehaviourNetworkSpawn()
{
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId);
@ -2238,6 +2250,42 @@ namespace Unity.Netcode
}
}
internal void InvokeBehaviourNetworkPostSpawn()
{
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
{
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
{
ChildNetworkBehaviours[i].NetworkPostSpawn();
}
}
}
internal void InternalNetworkSessionSynchronized()
{
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
{
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
{
ChildNetworkBehaviours[i].NetworkSessionSynchronized();
}
}
}
internal void InternalInSceneNetworkObjectsSpawned()
{
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
{
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
{
ChildNetworkBehaviours[i].InSceneNetworkObjectsSpawned();
}
}
}
internal void InvokeBehaviourNetworkDespawn()
{
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId, true);
@ -2862,6 +2910,9 @@ namespace Unity.Netcode
// in order to be able to determine which NetworkVariables the client will be allowed to read.
networkObject.OwnerClientId = sceneObject.OwnerClientId;
// Special Case: Invoke NetworkBehaviour.OnPreSpawn methods here before SynchronizeNetworkBehaviours
networkObject.InvokeBehaviourNetworkPreSpawn();
// Synchronize NetworkBehaviours
var bufferSerializer = new BufferSerializer<BufferSerializerReader>(new BufferSerializerReader(reader));
networkObject.SynchronizeNetworkBehaviours(ref bufferSerializer, networkManager.LocalClientId);
@ -3051,6 +3102,7 @@ namespace Unity.Netcode
private void Awake()
{
m_ChildNetworkBehaviours = null;
SetCachedParent(transform.parent);
SceneOrigin = gameObject.scene;
}

Просмотреть файл

@ -222,6 +222,12 @@ namespace Unity.Netcode
}
// When scene management is disabled we notify after everything is synchronized
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId);
// For convenience, notify all NetworkBehaviours that synchronization is complete.
foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList)
{
networkObject.InternalNetworkSessionSynchronized();
}
}
else
{

Просмотреть файл

@ -1859,6 +1859,17 @@ namespace Unity.Netcode
}
}
foreach (var keyValuePairByGlobalObjectIdHash in ScenePlacedObjects)
{
foreach (var keyValuePairBySceneHandle in keyValuePairByGlobalObjectIdHash.Value)
{
if (!keyValuePairBySceneHandle.Value.IsPlayerObject)
{
keyValuePairBySceneHandle.Value.InternalInSceneNetworkObjectsSpawned();
}
}
}
// Add any despawned when spawned in-scene placed NetworkObjects to the scene event data
sceneEventData.AddDespawnedInSceneNetworkObjects();
@ -2413,6 +2424,12 @@ namespace Unity.Netcode
{
NetworkLog.LogInfo($"[Client-{NetworkManager.LocalClientId}][Scene Management Enabled] Synchronization complete!");
}
// For convenience, notify all NetworkBehaviours that synchronization is complete.
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
{
networkObject.InternalNetworkSessionSynchronized();
}
EndSceneEvent(sceneEventId);
}
break;

Просмотреть файл

@ -839,7 +839,7 @@ namespace Unity.Netcode
{
// is not packed!
InternalBuffer.ReadValueSafe(out ushort newObjectsCount);
var sceneObjects = new List<NetworkObject>();
for (ushort i = 0; i < newObjectsCount; i++)
{
var sceneObject = new NetworkObject.SceneObject();
@ -851,10 +851,22 @@ namespace Unity.Netcode
m_NetworkManager.SceneManager.SetTheSceneBeingSynchronized(sceneObject.NetworkSceneHandle);
}
NetworkObject.AddSceneObject(sceneObject, InternalBuffer, m_NetworkManager);
var networkObject = NetworkObject.AddSceneObject(sceneObject, InternalBuffer, m_NetworkManager);
if (sceneObject.IsSceneObject)
{
sceneObjects.Add(networkObject);
}
}
// Now deserialize the despawned in-scene placed NetworkObjects list (if any)
DeserializeDespawnedInScenePlacedNetworkObjects();
// Notify all newly spawned in-scene placed NetworkObjects that all in-scene placed
// NetworkObjects have been spawned.
foreach (var networkObject in sceneObjects)
{
networkObject.InternalInSceneNetworkObjectsSpawned();
}
}
finally
{
@ -1122,6 +1134,15 @@ namespace Unity.Netcode
UnityEngine.Debug.Log(builder.ToString());
}
// Notify that all in-scene placed NetworkObjects have been spawned
foreach (var networkObject in m_NetworkObjectsSync)
{
if (networkObject.IsSceneObject.HasValue && networkObject.IsSceneObject.Value)
{
networkObject.InternalInSceneNetworkObjectsSpawned();
}
}
// Now deserialize the despawned in-scene placed NetworkObjects list (if any)
DeserializeDespawnedInScenePlacedNetworkObjects();

Просмотреть файл

@ -924,6 +924,8 @@ namespace Unity.Netcode
Debug.LogError("Spawning NetworkObjects with nested NetworkObjects is only supported for scene objects. Child NetworkObjects will not be spawned over the network!");
}
}
// Invoke NetworkBehaviour.OnPreSpawn methods
networkObject.InvokeBehaviourNetworkPreSpawn();
// DANGO-TODO: It would be nice to allow users to specify which clients are observers prior to spawning
// For now, this is the best place I could find to add all connected clients as observers for newly
@ -964,12 +966,18 @@ namespace Unity.Netcode
}
}
SpawnNetworkObjectLocallyCommon(networkObject, networkId, sceneObject, playerObject, ownerClientId, destroyWithScene);
// Invoke NetworkBehaviour.OnPostSpawn methods
networkObject.InvokeBehaviourNetworkPostSpawn();
}
/// <summary>
/// This is only invoked to instantiate a serialized NetworkObject via
/// <see cref="NetworkObject.AddSceneObject(in NetworkObject.SceneObject, FastBufferReader, NetworkManager, bool)"/>
/// </summary>
/// <remarks>
/// IMPORTANT: Pre spawn methods need to be invoked from within <see cref="NetworkObject.AddSceneObject"/>.
/// </remarks>
internal void SpawnNetworkObjectLocally(NetworkObject networkObject, in NetworkObject.SceneObject sceneObject, bool destroyWithScene)
{
if (networkObject == null)
@ -982,7 +990,11 @@ namespace Unity.Netcode
throw new SpawnStateException($"[{networkObject.name}] Object-{networkObject.NetworkObjectId} is already spawned!");
}
// Do not invoke Pre spawn here (SynchronizeNetworkBehaviours needs to be invoked prior to this)
SpawnNetworkObjectLocallyCommon(networkObject, sceneObject.NetworkObjectId, sceneObject.IsSceneObject, sceneObject.IsPlayerObject, sceneObject.OwnerClientId, destroyWithScene);
// It is ok to invoke NetworkBehaviour.OnPostSpawn methods
networkObject.InvokeBehaviourNetworkPostSpawn();
}
private void SpawnNetworkObjectLocallyCommon(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong ownerClientId, bool destroyWithScene)
@ -1314,6 +1326,7 @@ namespace Unity.Netcode
var networkObjects = UnityEngine.Object.FindObjectsOfType<NetworkObject>();
#endif
var isConnectedCMBService = NetworkManager.CMBServiceConnection;
var networkObjectsToSpawn = new List<NetworkObject>();
for (int i = 0; i < networkObjects.Length; i++)
{
if (networkObjects[i].NetworkManager == NetworkManager)
@ -1330,9 +1343,17 @@ namespace Unity.Netcode
}
SpawnNetworkObjectLocally(networkObjects[i], GetNetworkObjectId(), true, false, ownerId, true);
networkObjectsToSpawn.Add(networkObjects[i]);
}
}
}
// Notify all in-scene placed NetworkObjects have been spawned
foreach (var networkObject in networkObjectsToSpawn)
{
networkObject.InternalInSceneNetworkObjectsSpawned();
}
networkObjectsToSpawn.Clear();
}
internal void OnDespawnObject(NetworkObject networkObject, bool destroyGameObject, bool modeDestroy = false)

Просмотреть файл

@ -0,0 +1,143 @@
using System.Collections;
using NUnit.Framework;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using UnityEngine.TestTools;
namespace Unity.Netcode.RuntimeTests
{
[TestFixture(HostOrServer.Host)]
[TestFixture(HostOrServer.DAHost)]
public class NetworkBehaviourPrePostSpawnTests : NetcodeIntegrationTest
{
protected override int NumberOfClients => 0;
private bool m_AllowServerToStart;
private GameObject m_PrePostSpawnObject;
public NetworkBehaviourPrePostSpawnTests(HostOrServer hostOrServer) : base(hostOrServer) { }
protected override void OnServerAndClientsCreated()
{
m_PrePostSpawnObject = CreateNetworkObjectPrefab("PrePostSpawn");
// Reverse the order of the components to get inverted spawn sequence
m_PrePostSpawnObject.AddComponent<NetworkBehaviourPostSpawn>();
m_PrePostSpawnObject.AddComponent<NetworkBehaviourPreSpawn>();
base.OnServerAndClientsCreated();
}
public class NetworkBehaviourPreSpawn : NetworkBehaviour
{
public static int ValueToSet;
public bool OnNetworkPreSpawnCalled;
public bool NetworkVarValueMatches;
public NetworkVariable<int> TestNetworkVariable;
protected override void OnNetworkPreSpawn(ref NetworkManager networkManager)
{
OnNetworkPreSpawnCalled = true;
// If we are the server, then set the randomly generated value (1-200).
// Otherwise, just set the value to 0.
// TODO: Make adjustments when integrated CMB service testing is added
var val = networkManager.IsServer ? ValueToSet : 0;
// Instantiate the NetworkVariable as everyone read & owner write while also setting the value
TestNetworkVariable = new NetworkVariable<int>(val, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
base.OnNetworkPreSpawn(ref networkManager);
}
public override void OnNetworkSpawn()
{
// For both client and server this should match at this point
NetworkVarValueMatches = TestNetworkVariable.Value == ValueToSet;
base.OnNetworkSpawn();
}
}
public class NetworkBehaviourPostSpawn : NetworkBehaviour
{
public bool OnNetworkPostSpawnCalled;
private NetworkBehaviourPreSpawn m_NetworkBehaviourPreSpawn;
public int ValueSet;
public override void OnNetworkSpawn()
{
// Obtain the NetworkBehaviourPreSpawn component
// (could also do this during OnNetworkPreSpawn if we wanted)
m_NetworkBehaviourPreSpawn = GetComponent<NetworkBehaviourPreSpawn>();
base.OnNetworkSpawn();
}
protected override void OnNetworkPostSpawn()
{
OnNetworkPostSpawnCalled = true;
// We should be able to access the component we got during OnNetworkSpawn and all values should be set
// (i.e. OnNetworkSpawn run on all NetworkObject relative NetworkBehaviours)
ValueSet = m_NetworkBehaviourPreSpawn.TestNetworkVariable.Value;
base.OnNetworkPostSpawn();
}
}
protected override bool CanStartServerAndClients()
{
return m_AllowServerToStart;
}
protected override IEnumerator OnSetup()
{
m_AllowServerToStart = false;
return base.OnSetup();
}
protected override void OnNewClientCreated(NetworkManager networkManager)
{
networkManager.NetworkConfig.Prefabs = m_ServerNetworkManager.NetworkConfig.Prefabs;
base.OnNewClientCreated(networkManager);
}
/// <summary>
/// This validates that pre spawn can be used to instantiate and assign a NetworkVariable (or other prespawn tasks)
/// which can be useful for assigning a NetworkVariable value on the server side when the NetworkVariable has owner write permissions.
/// This also assures that duruing post spawn all associated NetworkBehaviours have run through the OnNetworkSpawn pass (i.e. OnNetworkSpawn order is not an issue)
/// </summary>
[UnityTest]
public IEnumerator OnNetworkPreAndPostSpawn()
{
m_AllowServerToStart = true;
NetworkBehaviourPreSpawn.ValueToSet = Random.Range(1, 200);
yield return StartServerAndClients();
yield return CreateAndStartNewClient();
// Spawn the object with the newly joined client as the owner
var networkManager = m_DistributedAuthority ? m_ServerNetworkManager : m_ClientNetworkManagers[0];
var authorityInstance = SpawnObject(m_PrePostSpawnObject, networkManager);
var authorityNetworkObject = authorityInstance.GetComponent<NetworkObject>();
var authorityPreSpawn = authorityInstance.GetComponent<NetworkBehaviourPreSpawn>();
var authorityPostSpawn = authorityInstance.GetComponent<NetworkBehaviourPostSpawn>();
yield return WaitForConditionOrTimeOut(() => s_GlobalNetworkObjects.ContainsKey(m_ClientNetworkManagers[0].LocalClientId)
&& s_GlobalNetworkObjects[m_ClientNetworkManagers[0].LocalClientId].ContainsKey(authorityNetworkObject.NetworkObjectId));
AssertOnTimeout($"Client-{m_ClientNetworkManagers[0].LocalClientId} failed to spawn {nameof(NetworkObject)} id-{authorityNetworkObject.NetworkObjectId}!");
var clientNetworkObject = s_GlobalNetworkObjects[m_ClientNetworkManagers[0].LocalClientId][authorityNetworkObject.NetworkObjectId];
var clientPreSpawn = clientNetworkObject.GetComponent<NetworkBehaviourPreSpawn>();
var clientPostSpawn = clientNetworkObject.GetComponent<NetworkBehaviourPostSpawn>();
Assert.IsTrue(authorityPreSpawn.OnNetworkPreSpawnCalled, $"[Authority-side] OnNetworkPreSpawn not invoked!");
Assert.IsTrue(clientPreSpawn.OnNetworkPreSpawnCalled, $"[Client-side] OnNetworkPreSpawn not invoked!");
Assert.IsTrue(authorityPostSpawn.OnNetworkPostSpawnCalled, $"[Authority-side] OnNetworkPostSpawn not invoked!");
Assert.IsTrue(clientPostSpawn.OnNetworkPostSpawnCalled, $"[Client-side] OnNetworkPostSpawn not invoked!");
Assert.IsTrue(authorityPreSpawn.NetworkVarValueMatches, $"[Authority-side][PreSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {authorityPreSpawn.TestNetworkVariable.Value}!");
Assert.IsTrue(clientPreSpawn.NetworkVarValueMatches, $"[Client-side][PreSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {clientPreSpawn.TestNetworkVariable.Value}!");
Assert.IsTrue(authorityPostSpawn.ValueSet == NetworkBehaviourPreSpawn.ValueToSet, $"[Authority-side][PostSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {authorityPostSpawn.ValueSet}!");
Assert.IsTrue(clientPostSpawn.ValueSet == NetworkBehaviourPreSpawn.ValueToSet, $"[Client-side][PostSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {clientPostSpawn.ValueSet}!");
}
}
}

Просмотреть файл

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2263d66f6df15a7428d279dbdaba1519
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

Просмотреть файл

@ -0,0 +1,62 @@
using Unity.Netcode;
using UnityEngine;
namespace TestProject.ManualTests
{
public class SessionSynchronizedTest : NetworkBehaviour
{
public static SessionSynchronizedTest FirstObject;
public static SessionSynchronizedTest SecondObject;
public SessionSynchronizedTest ObjectForServerToReference;
public NetworkVariable<NetworkBehaviourReference> OtherObject = new NetworkVariable<NetworkBehaviourReference>();
public bool IsFirstObject;
public bool OnInSceneObjectsSpawnedInvoked;
[Range(1, 1000)]
public int ValueToCheck;
public int OtherValueObtained;
public SessionSynchronizedTest ClientSideReferencedBehaviour;
protected override void OnNetworkPreSpawn(ref NetworkManager networkManager)
{
if (!networkManager.IsServer)
{
if (IsFirstObject)
{
FirstObject = this;
}
else
{
SecondObject = this;
}
}
base.OnNetworkPreSpawn(ref networkManager);
}
protected override void OnNetworkSessionSynchronized()
{
if (!HasAuthority)
{
OtherObject.Value.TryGet(out ClientSideReferencedBehaviour, NetworkManager);
OtherValueObtained = ClientSideReferencedBehaviour.ValueToCheck;
}
base.OnNetworkSessionSynchronized();
}
/// <summary>
/// Tests the in-scene objects spawned method gets invoked after a scene has been loaded and the associated in-scene placed NetworkObjects
/// have been spawned.
/// </summary>
protected override void OnInSceneObjectsSpawned()
{
if (HasAuthority)
{
OtherObject.Value = new NetworkBehaviourReference(ObjectForServerToReference);
}
OnInSceneObjectsSpawnedInvoked = true;
base.OnInSceneObjectsSpawned();
}
}
}

Просмотреть файл

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 231239ca566ad7e4da43fd99c4601378
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

Просмотреть файл

@ -0,0 +1,271 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!29 &1
OcclusionCullingSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
m_OcclusionBakeSettings:
smallestOccluder: 5
smallestHole: 0.25
backfaceThreshold: 100
m_SceneGUID: 00000000000000000000000000000000
m_OcclusionCullingData: {fileID: 0}
--- !u!104 &2
RenderSettings:
m_ObjectHideFlags: 0
serializedVersion: 9
m_Fog: 0
m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}
m_FogMode: 3
m_FogDensity: 0.01
m_LinearFogStart: 0
m_LinearFogEnd: 300
m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1}
m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}
m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}
m_AmbientIntensity: 1
m_AmbientMode: 0
m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1}
m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0}
m_HaloStrength: 0.5
m_FlareStrength: 1
m_FlareFadeSpeed: 3
m_HaloTexture: {fileID: 0}
m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}
m_DefaultReflectionMode: 0
m_DefaultReflectionResolution: 128
m_ReflectionBounces: 1
m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.37311953, g: 0.38074014, b: 0.3587274, a: 1}
m_UseRadianceAmbientProbe: 0
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 12
m_GIWorkflowMode: 1
m_GISettings:
serializedVersion: 2
m_BounceScale: 1
m_IndirectOutputScale: 1
m_AlbedoBoost: 1
m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableRealtimeLightmaps: 0
m_LightmapEditorSettings:
serializedVersion: 12
m_Resolution: 2
m_BakeResolution: 40
m_AtlasSize: 1024
m_AO: 0
m_AOMaxDistance: 1
m_CompAOExponent: 1
m_CompAOExponentDirect: 0
m_ExtractAmbientOcclusion: 0
m_Padding: 2
m_LightmapParameters: {fileID: 0}
m_LightmapsBakeMode: 1
m_TextureCompression: 1
m_FinalGather: 0
m_FinalGatherFiltering: 1
m_FinalGatherRayCount: 256
m_ReflectionCompression: 2
m_MixedBakeMode: 2
m_BakeBackend: 1
m_PVRSampling: 1
m_PVRDirectSampleCount: 32
m_PVRSampleCount: 512
m_PVRBounces: 2
m_PVREnvironmentSampleCount: 256
m_PVREnvironmentReferencePointCount: 2048
m_PVRFilteringMode: 1
m_PVRDenoiserTypeDirect: 1
m_PVRDenoiserTypeIndirect: 1
m_PVRDenoiserTypeAO: 1
m_PVRFilterTypeDirect: 0
m_PVRFilterTypeIndirect: 0
m_PVRFilterTypeAO: 0
m_PVREnvironmentMIS: 1
m_PVRCulling: 1
m_PVRFilteringGaussRadiusDirect: 1
m_PVRFilteringGaussRadiusIndirect: 5
m_PVRFilteringGaussRadiusAO: 2
m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_ExportTrainingData: 0
m_TrainingDataDestination: TrainingData
m_LightProbeSampleCountMultiplier: 4
m_LightingDataAsset: {fileID: 0}
m_LightingSettings: {fileID: 0}
--- !u!196 &4
NavMeshSettings:
serializedVersion: 2
m_ObjectHideFlags: 0
m_BuildSettings:
serializedVersion: 3
agentTypeID: 0
agentRadius: 0.5
agentHeight: 2
agentSlope: 45
agentClimb: 0.4
ledgeDropHeight: 0
maxJumpAcrossDistance: 0
minRegionArea: 2
manualCellSize: 0
cellSize: 0.16666667
manualTileSize: 0
tileSize: 256
buildHeightMesh: 0
maxJobWorkers: 0
preserveTilesOutsideBounds: 0
debug:
m_Flags: 0
m_NavMeshData: {fileID: 0}
--- !u!1 &470552562
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 470552565}
- component: {fileID: 470552563}
- component: {fileID: 470552564}
m_Layer: 0
m_Name: FirstInSceneObject
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &470552563
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 470552562}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: d5a57f767e5e46a458fc5d3c628d0cbb, type: 3}
m_Name:
m_EditorClassIdentifier:
GlobalObjectIdHash: 99604880
InScenePlacedSourceGlobalObjectIdHash: 0
AlwaysReplicateAsRoot: 0
SynchronizeTransform: 1
ActiveSceneSynchronization: 0
SceneMigrationSynchronization: 1
SpawnWithObservers: 1
DontDestroyWithOwner: 0
AutoObjectParentSync: 1
--- !u!114 &470552564
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 470552562}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 231239ca566ad7e4da43fd99c4601378, type: 3}
m_Name:
m_EditorClassIdentifier:
ObjectForServerToReference: {fileID: 1617529774}
IsFirstObject: 1
ValueToCheck: 250
OtherValueObtained: 0
--- !u!4 &470552565
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 470552562}
serializedVersion: 2
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1617529773
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1617529775}
- component: {fileID: 1617529776}
- component: {fileID: 1617529774}
m_Layer: 0
m_Name: SecondInSceneObject
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &1617529774
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1617529773}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 231239ca566ad7e4da43fd99c4601378, type: 3}
m_Name:
m_EditorClassIdentifier:
ObjectForServerToReference: {fileID: 470552564}
IsFirstObject: 0
ValueToCheck: 600
OtherValueObtained: 0
--- !u!4 &1617529775
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1617529773}
serializedVersion: 2
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &1617529776
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1617529773}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: d5a57f767e5e46a458fc5d3c628d0cbb, type: 3}
m_Name:
m_EditorClassIdentifier:
GlobalObjectIdHash: 3716379494
InScenePlacedSourceGlobalObjectIdHash: 0
AlwaysReplicateAsRoot: 0
SynchronizeTransform: 1
ActiveSceneSynchronization: 0
SceneMigrationSynchronization: 1
SpawnWithObservers: 1
DontDestroyWithOwner: 0
AutoObjectParentSync: 1
--- !u!1660057539 &9223372036854775807
SceneRoots:
m_ObjectHideFlags: 0
m_Roots:
- {fileID: 470552565}
- {fileID: 1617529775}

Просмотреть файл

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 468b795904b98234593ebc31bf0d578a
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Просмотреть файл

@ -0,0 +1,51 @@
using System.Collections;
using NUnit.Framework;
using TestProject.ManualTests;
using Unity.Netcode;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine.TestTools;
namespace TestProject.RuntimeTests
{
[TestFixture(HostOrServer.Host)]
[TestFixture(HostOrServer.DAHost)]
public class NetworkBehaviourSessionSynchronized : NetcodeIntegrationTest
{
private const string k_SceneToLoad = "SessionSynchronize";
protected override int NumberOfClients => 0;
private bool m_SceneLoaded;
public NetworkBehaviourSessionSynchronized(HostOrServer hostOrServer) : base(hostOrServer) { }
[UnityTest]
public IEnumerator InScenePlacedSessionSynchronized()
{
m_SceneLoaded = false;
m_ServerNetworkManager.SceneManager.OnSceneEvent += OnSceneEvent;
m_ServerNetworkManager.SceneManager.LoadScene(k_SceneToLoad, UnityEngine.SceneManagement.LoadSceneMode.Additive);
yield return WaitForConditionOrTimeOut(() => m_SceneLoaded);
AssertOnTimeout($"Timed out waiting for scene {k_SceneToLoad} to load!");
yield return CreateAndStartNewClient();
AssertOnTimeout($"Timed out waiting for client to join session!");
var firstObject = SessionSynchronizedTest.FirstObject;
var secondObject = SessionSynchronizedTest.SecondObject;
Assert.True(firstObject == secondObject.ClientSideReferencedBehaviour);
Assert.True(secondObject == firstObject.ClientSideReferencedBehaviour);
Assert.True(firstObject.OtherValueObtained == secondObject.ValueToCheck);
Assert.True(secondObject.OtherValueObtained == firstObject.ValueToCheck);
Assert.True(firstObject.OnInSceneObjectsSpawnedInvoked);
Assert.True(secondObject.OnInSceneObjectsSpawnedInvoked);
}
private void OnSceneEvent(SceneEvent sceneEvent)
{
if (sceneEvent.ClientId == m_ServerNetworkManager.LocalClientId && sceneEvent.SceneEventType == SceneEventType.LoadEventCompleted)
{
m_SceneLoaded = true;
m_ServerNetworkManager.SceneManager.OnSceneEvent -= OnSceneEvent;
}
}
}
}

Просмотреть файл

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3bc1044db79cdcb41bc37e7e906e966f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

Просмотреть файл

@ -149,6 +149,9 @@ EditorBuildSettings:
- enabled: 1
path: Assets/Tests/Manual/IntegrationTestScenes/InSceneUnderGameObjectWithNT.unity
guid: 5a4f489df08d16c4d8c0167b099de2ca
- enabled: 1
path: Assets/Tests/Manual/IntegrationTestScenes/SessionSynchronize.unity
guid: 468b795904b98234593ebc31bf0d578a
m_configObjects:
com.unity.addressableassets: {fileID: 11400000, guid: 5a3d5c53c25349c48912726ae850f3b0,
type: 2}