com.unity.netcode.gameobjects@1.4.0

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).

## [1.4.0] - 2023-04-10

### Added

- Added a way to access the GlobalObjectIdHash via PrefabIdHash for use in the Connection Approval Callback. (#2437)
- Added `OnServerStarted` and `OnServerStopped` events that will trigger only on the server (or host player) to notify that the server just started or is no longer active (#2420)
- Added `OnClientStarted` and `OnClientStopped` events that will trigger only on the client (or host player) to notify that the client just started or is no longer active (#2420)
- Added `NetworkTransform.UseHalfFloatPrecision` property that, when enabled, will use half float values for position, rotation, and scale. This yields a 50% bandwidth savings a the cost of precision. (#2388)
- Added `NetworkTransform.UseQuaternionSynchronization` property that, when enabled, will synchronize the entire quaternion. (#2388)
- Added `NetworkTransform.UseQuaternionCompression` property that, when enabled, will use a smallest three implementation reducing a full quaternion synchronization update to the size of an unsigned integer. (#2388)
- Added `NetworkTransform.SlerpPosition` property that, when enabled along with interpolation being enabled, will interpolate using `Vector3.Slerp`. (#2388)
- Added `BufferedLinearInterpolatorVector3` that replaces the float version, is now used by `NetworkTransform`, and provides the ability to enable or disable `Slerp`. (#2388)
- Added `HalfVector3` used for scale when half float precision is enabled. (#2388)
- Added `HalfVector4` used for rotation when half float precision and quaternion synchronization is enabled. (#2388)
- Added `HalfVector3DeltaPosition` used for position when half float precision is enabled. This handles loss in position precision by updating only the delta position as opposed to the full position. (#2388)
- Added `NetworkTransform.GetSpaceRelativePosition` and `NetworkTransform.GetSpaceRelativeRotation` helper methods to return the proper values depending upon whether local or world space. (#2388)
- Added `NetworkTransform.OnAuthorityPushTransformState` virtual method that is invoked just prior to sending the `NetworkTransformState` to non-authoritative instances. This provides users with the ability to obtain more precise delta values for prediction related calculations. (#2388)
- Added `NetworkTransform.OnNetworkTransformStateUpdated` virtual method that is invoked just after the authoritative `NetworkTransformState` is applied. This provides users with the ability to obtain more precise delta values for prediction related calculations. (#2388)
- Added `NetworkTransform.OnInitialize`virtual method that is invoked after the `NetworkTransform` has been initialized or re-initialized when ownership changes. This provides for a way to make adjustments when `NetworkTransform` is initialized (i.e. resetting client prediction etc) (#2388)
- Added `NetworkObject.SynchronizeTransform` property (default is true) that provides users with another way to help with bandwidth optimizations where, when set to false, the `NetworkObject`'s associated transform will not be included when spawning and/or synchronizing late joining players. (#2388)
- Added `NetworkSceneManager.ActiveSceneSynchronizationEnabled` property, disabled by default, that enables client synchronization of server-side active scene changes. (#2383)
- Added `NetworkObject.ActiveSceneSynchronization`, disabled by default, that will automatically migrate a `NetworkObject` to a newly assigned active scene. (#2383)
- Added `NetworkObject.SceneMigrationSynchronization`, enabled by default, that will synchronize client(s) when a `NetworkObject` is migrated into a new scene on the server side via `SceneManager.MoveGameObjectToScene`. (#2383)

### Changed

- Made sure the `CheckObjectVisibility` delegate is checked and applied, upon `NetworkShow` attempt. Found while supporting (#2454), although this is not a fix for this (already fixed) issue. (#2463)
- Changed `NetworkTransform` authority handles delta checks on each new network tick and no longer consumes processing cycles checking for deltas for all frames in-between ticks. (#2388)
- Changed the `NetworkTransformState` structure is now public and now has public methods that provide access to key properties of the `NetworkTransformState` structure. (#2388)
- Changed `NetworkTransform` interpolation adjusts its interpolation "ticks ago" to be 2 ticks latent if it is owner authoritative and the instance is not the server or 1 tick latent if the instance is the server and/or is server authoritative. (#2388)
- Updated `NetworkSceneManager` to migrate dynamically spawned `NetworkObject`s with `DestroyWithScene` set to false into the active scene if their current scene is unloaded. (#2383)
- Updated the server to synchronize its local `NetworkSceneManager.ClientSynchronizationMode` during the initial client synchronization. (#2383)

### Fixed

- Fixed issue where during client synchronization the synchronizing client could receive a ObjectSceneChanged message before the client-side NetworkObject instance had been instantiated and spawned. (#2502)
- Fixed issue where `NetworkAnimator` was building client RPC parameters to exclude the host from sending itself messages but was not including it in the ClientRpc parameters. (#2492)
- Fixed issue where `NetworkAnimator` was not properly detecting and synchronizing cross fade initiated transitions. (#2481)
- Fixed issue where `NetworkAnimator` was not properly synchronizing animation state updates. (#2481)
- Fixed float NetworkVariables not being rendered properly in the inspector of NetworkObjects. (#2441)
- Fixed an issue where Named Message Handlers could remove themselves causing an exception when the metrics tried to access the name of the message.(#2426)
- Fixed registry of public `NetworkVariable`s in derived `NetworkBehaviour`s (#2423)
- Fixed issue where runtime association of `Animator` properties to `AnimationCurve`s would cause `NetworkAnimator` to attempt to update those changes. (#2416)
- Fixed issue where `NetworkAnimator` would not check if its associated `Animator` was valid during serialization and would spam exceptions in the editor console. (#2416)
- Fixed issue with a child's rotation rolling over when interpolation is enabled on a `NetworkTransform`. Now using half precision or full quaternion synchronization will always update all axis. (#2388)
- Fixed issue where `NetworkTransform` was not setting the teleport flag when the `NetworkTransform.InLocalSpace` value changed. This issue only impacted `NetworkTransform` when interpolation was enabled. (#2388)
- Fixed issue when the `NetworkSceneManager.ClientSynchronizationMode` is `LoadSceneMode.Additive` and the server changes the currently active scene prior to a client connecting then upon a client connecting and being synchronized the NetworkSceneManager would clear its internal ScenePlacedObjects list that could already be populated. (#2383)
- Fixed issue where a client would load duplicate scenes of already preloaded scenes during the initial client synchronization and `NetworkSceneManager.ClientSynchronizationMode` was set to `LoadSceneMode.Additive`. (#2383)
This commit is contained in:
Unity Technologies
2023-04-10 00:00:00 +00:00
parent 8060718e04
commit b5abc3ff7c
138 changed files with 7892 additions and 1852 deletions

View File

@@ -1,12 +1,13 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.TestTools;
using System.Linq;
using NUnit.Framework;
using Unity.Collections;
using Unity.Netcode.TestHelpers.Runtime;
using Random = UnityEngine.Random;
using UnityEngine;
using UnityEngine.TestTools;
using Random = UnityEngine.Random;
namespace Unity.Netcode.RuntimeTests
{
@@ -17,6 +18,22 @@ namespace Unity.Netcode.RuntimeTests
public NetworkVariable<Vector3> OwnerReadWrite_Position = new NetworkVariable<Vector3>(Vector3.one, NetworkVariableReadPermission.Owner, NetworkVariableWritePermission.Owner);
}
public class NetworkVariableMiddleclass<TMiddleclassName> : NetworkVariable<TMiddleclassName>
{
}
public class NetworkVariableSubclass<TSubclassName> : NetworkVariableMiddleclass<TSubclassName>
{
}
public struct TemplatedValueOnlyReferencedByNetworkVariableSubclass<T> : INetworkSerializeByMemcpy
where T : unmanaged
{
public T Value;
}
// The ILPP code for NetworkVariables to determine how to serialize them relies on them existing as fields of a NetworkBehaviour to find them.
// Some of the tests below create NetworkVariables on the stack, so this class is here just to make sure the relevant types are all accounted for.
public class NetVarILPPClassForTests : NetworkBehaviour
@@ -25,6 +42,7 @@ namespace Unity.Netcode.RuntimeTests
public NetworkVariable<ManagedNetworkSerializableType> ManagedNetworkSerializableTypeVar;
public NetworkVariable<string> StringVar;
public NetworkVariable<Guid> GuidVar;
public NetworkVariableSubclass<TemplatedValueOnlyReferencedByNetworkVariableSubclass<int>> SubclassVar;
}
public class TemplateNetworkBehaviourType<T> : NetworkBehaviour
@@ -500,6 +518,10 @@ namespace Unity.Netcode.RuntimeTests
private const int k_TestVal2 = 222;
private const int k_TestVal3 = 333;
protected override bool m_EnableTimeTravel => true;
protected override bool m_SetupIsACoroutine => false;
protected override bool m_TearDownIsACoroutine => false;
private static List<NetworkVariableTest> s_ClientNetworkVariableTestInstances = new List<NetworkVariableTest>();
public static void ClientNetworkVariableTestSpawned(NetworkVariableTest networkVariableTest)
{
@@ -530,7 +552,7 @@ namespace Unity.Netcode.RuntimeTests
/// This is an adjustment to how the server and clients are started in order
/// to avoid timing issues when running in a stand alone test runner build.
/// </summary>
private IEnumerator InitializeServerAndClients(bool useHost)
private void InitializeServerAndClients(bool useHost)
{
s_ClientNetworkVariableTestInstances.Clear();
m_PlayerPrefab.AddComponent<NetworkVariableTest>();
@@ -552,13 +574,13 @@ namespace Unity.Netcode.RuntimeTests
RegisterSceneManagerHandler();
// Wait for connection on client and server side
yield return WaitForClientsConnectedOrTimeOut();
AssertOnTimeout($"Timed-out waiting for all clients to connect!");
var success = WaitForClientsConnectedOrTimeOutWithTimeTravel();
Assert.True(success, $"Timed-out waiting for all clients to connect!");
// These are the *SERVER VERSIONS* of the *CLIENT PLAYER 1 & 2*
var result = new NetcodeIntegrationTestHelpers.ResultWrapper<NetworkObject>();
yield return NetcodeIntegrationTestHelpers.GetNetworkObjectByRepresentation(
NetcodeIntegrationTestHelpers.GetNetworkObjectByRepresentationWithTimeTravel(
x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId,
m_ServerNetworkManager, result);
@@ -566,7 +588,7 @@ namespace Unity.Netcode.RuntimeTests
m_Player1OnServer = result.Result.GetComponent<NetworkVariableTest>();
// This is client1's view of itself
yield return NetcodeIntegrationTestHelpers.GetNetworkObjectByRepresentation(
NetcodeIntegrationTestHelpers.GetNetworkObjectByRepresentationWithTimeTravel(
x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId,
m_ClientNetworkManagers[0], result);
@@ -586,18 +608,18 @@ namespace Unity.Netcode.RuntimeTests
var instanceCount = useHost ? NumberOfClients * 3 : NumberOfClients * 2;
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(() => s_ClientNetworkVariableTestInstances.Count == instanceCount);
success = WaitForConditionOrTimeOutWithTimeTravel(() => s_ClientNetworkVariableTestInstances.Count == instanceCount);
Assert.False(s_GlobalTimeoutHelper.TimedOut, "Timed out waiting for all client NetworkVariableTest instances to register they have spawned!");
Assert.True(success, "Timed out waiting for all client NetworkVariableTest instances to register they have spawned!");
yield return s_DefaultWaitForTick;
TimeTravelToNextTick();
}
/// <summary>
/// Runs generalized tests on all predefined NetworkVariable types
/// </summary>
[UnityTest]
public IEnumerator AllNetworkVariableTypes([Values(true, false)] bool useHost)
[Test]
public void AllNetworkVariableTypes([Values(true, false)] bool useHost)
{
// Create, instantiate, and host
// This would normally go in Setup, but since every other test but this one
@@ -616,8 +638,8 @@ namespace Unity.Netcode.RuntimeTests
// Start Testing
networkVariableTestComponent.EnableTesting = true;
yield return WaitForConditionOrTimeOut(() => true == networkVariableTestComponent.IsTestComplete());
Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, "Timed out waiting for the test to complete!");
var success = WaitForConditionOrTimeOutWithTimeTravel(() => true == networkVariableTestComponent.IsTestComplete());
Assert.True(success, "Timed out waiting for the test to complete!");
// Stop Testing
networkVariableTestComponent.EnableTesting = false;
@@ -634,10 +656,10 @@ namespace Unity.Netcode.RuntimeTests
NetworkManagerHelper.ShutdownNetworkManager();
}
[UnityTest]
public IEnumerator ClientWritePermissionTest([Values(true, false)] bool useHost)
[Test]
public void ClientWritePermissionTest([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
// client must not be allowed to write to a server auth variable
Assert.Throws<InvalidOperationException>(() => m_Player1OnClient1.TheScalar.Value = k_TestVal1);
@@ -646,63 +668,63 @@ namespace Unity.Netcode.RuntimeTests
/// <summary>
/// Runs tests that network variables sync on client whatever the local value of <see cref="Time.timeScale"/>.
/// </summary>
[UnityTest]
public IEnumerator NetworkVariableSync_WithDifferentTimeScale([Values(true, false)] bool useHost, [Values(0.0f, 1.0f, 2.0f)] float timeScale)
[Test]
public void NetworkVariableSync_WithDifferentTimeScale([Values(true, false)] bool useHost, [Values(0.0f, 1.0f, 2.0f)] float timeScale)
{
Time.timeScale = timeScale;
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
m_Player1OnServer.TheScalar.Value = k_TestVal1;
// Now wait for the client side version to be updated to k_TestVal1
yield return WaitForConditionOrTimeOut(() => m_Player1OnClient1.TheScalar.Value == k_TestVal1);
Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, "Timed out waiting for client-side NetworkVariable to update!");
var success = WaitForConditionOrTimeOutWithTimeTravel(() => m_Player1OnClient1.TheScalar.Value == k_TestVal1);
Assert.True(success, "Timed out waiting for client-side NetworkVariable to update!");
}
[UnityTest]
public IEnumerator FixedString32Test([Values(true, false)] bool useHost)
[Test]
public void FixedString32Test([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
m_Player1OnServer.FixedString32.Value = k_FixedStringTestValue;
// Now wait for the client side version to be updated to k_FixedStringTestValue
yield return WaitForConditionOrTimeOut(() => m_Player1OnClient1.FixedString32.Value == k_FixedStringTestValue);
Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, "Timed out waiting for client-side NetworkVariable to update!");
var success = WaitForConditionOrTimeOutWithTimeTravel(() => m_Player1OnClient1.FixedString32.Value == k_FixedStringTestValue);
Assert.True(success, "Timed out waiting for client-side NetworkVariable to update!");
}
[UnityTest]
public IEnumerator NetworkListAdd([Values(true, false)] bool useHost)
[Test]
public void NetworkListAdd([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
m_NetworkListPredicateHandler = new NetworkListTestPredicate(m_Player1OnServer, m_Player1OnClient1, NetworkListTestPredicate.NetworkListTestStates.Add, 10);
yield return WaitForConditionOrTimeOut(m_NetworkListPredicateHandler);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(m_NetworkListPredicateHandler));
}
[UnityTest]
public IEnumerator WhenListContainsManyLargeValues_OverflowExceptionIsNotThrown([Values(true, false)] bool useHost)
[Test]
public void WhenListContainsManyLargeValues_OverflowExceptionIsNotThrown([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
m_NetworkListPredicateHandler = new NetworkListTestPredicate(m_Player1OnServer, m_Player1OnClient1, NetworkListTestPredicate.NetworkListTestStates.ContainsLarge, 20);
yield return WaitForConditionOrTimeOut(m_NetworkListPredicateHandler);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(m_NetworkListPredicateHandler));
}
[UnityTest]
public IEnumerator NetworkListContains([Values(true, false)] bool useHost)
[Test]
public void NetworkListContains([Values(true, false)] bool useHost)
{
// Re-use the NetworkListAdd to initialize the server and client as well as make sure the list is populated
yield return NetworkListAdd(useHost);
NetworkListAdd(useHost);
// Now test the NetworkList.Contains method
m_NetworkListPredicateHandler.SetNetworkListTestState(NetworkListTestPredicate.NetworkListTestStates.Contains);
yield return WaitForConditionOrTimeOut(m_NetworkListPredicateHandler);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(m_NetworkListPredicateHandler));
}
[UnityTest]
public IEnumerator NetworkListRemove([Values(true, false)] bool useHost)
[Test]
public void NetworkListRemove([Values(true, false)] bool useHost)
{
// Re-use the NetworkListAdd to initialize the server and client as well as make sure the list is populated
yield return NetworkListAdd(useHost);
NetworkListAdd(useHost);
// Remove two entries by index
m_Player1OnServer.TheList.Remove(3);
@@ -710,41 +732,41 @@ namespace Unity.Netcode.RuntimeTests
// Really just verifies the data at this point
m_NetworkListPredicateHandler.SetNetworkListTestState(NetworkListTestPredicate.NetworkListTestStates.VerifyData);
yield return WaitForConditionOrTimeOut(m_NetworkListPredicateHandler);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(m_NetworkListPredicateHandler));
}
[UnityTest]
public IEnumerator NetworkListInsert([Values(true, false)] bool useHost)
[Test]
public void NetworkListInsert([Values(true, false)] bool useHost)
{
// Re-use the NetworkListAdd to initialize the server and client as well as make sure the list is populated
yield return NetworkListAdd(useHost);
NetworkListAdd(useHost);
// Now randomly insert a random value entry
m_Player1OnServer.TheList.Insert(Random.Range(0, 9), Random.Range(1, 99));
// Verify the element count and values on the client matches the server
m_NetworkListPredicateHandler.SetNetworkListTestState(NetworkListTestPredicate.NetworkListTestStates.VerifyData);
yield return WaitForConditionOrTimeOut(m_NetworkListPredicateHandler);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(m_NetworkListPredicateHandler));
}
[UnityTest]
public IEnumerator NetworkListIndexOf([Values(true, false)] bool useHost)
[Test]
public void NetworkListIndexOf([Values(true, false)] bool useHost)
{
// Re-use the NetworkListAdd to initialize the server and client as well as make sure the list is populated
yield return NetworkListAdd(useHost);
NetworkListAdd(useHost);
m_NetworkListPredicateHandler.SetNetworkListTestState(NetworkListTestPredicate.NetworkListTestStates.IndexOf);
yield return WaitForConditionOrTimeOut(m_NetworkListPredicateHandler);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(m_NetworkListPredicateHandler));
}
[UnityTest]
public IEnumerator NetworkListValueUpdate([Values(true, false)] bool useHost)
[Test]
public void NetworkListValueUpdate([Values(true, false)] bool useHost)
{
var testSucceeded = false;
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
// Add 1 element value and verify it is the same on the client
m_NetworkListPredicateHandler = new NetworkListTestPredicate(m_Player1OnServer, m_Player1OnClient1, NetworkListTestPredicate.NetworkListTestStates.Add, 1);
yield return WaitForConditionOrTimeOut(m_NetworkListPredicateHandler);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(m_NetworkListPredicateHandler));
// Setup our original and
var previousValue = m_Player1OnServer.TheList[0];
@@ -763,17 +785,17 @@ namespace Unity.Netcode.RuntimeTests
// Wait until we know the client side matches the server side before checking if the callback was a success
m_NetworkListPredicateHandler.SetNetworkListTestState(NetworkListTestPredicate.NetworkListTestStates.VerifyData);
yield return WaitForConditionOrTimeOut(m_NetworkListPredicateHandler);
WaitForConditionOrTimeOutWithTimeTravel(m_NetworkListPredicateHandler);
Assert.That(testSucceeded);
m_Player1OnClient1.TheList.OnListChanged -= TestValueUpdatedCallback;
}
[UnityTest]
public IEnumerator NetworkListRemoveAt([Values(true, false)] bool useHost)
[Test]
public void NetworkListRemoveAt([Values(true, false)] bool useHost)
{
// Re-use the NetworkListAdd to initialize the server and client as well as make sure the list is populated
yield return NetworkListAdd(useHost);
NetworkListAdd(useHost);
// Randomly remove a few entries
m_Player1OnServer.TheList.RemoveAt(Random.Range(0, m_Player1OnServer.TheList.Count - 1));
@@ -782,24 +804,24 @@ namespace Unity.Netcode.RuntimeTests
// Verify the element count and values on the client matches the server
m_NetworkListPredicateHandler.SetNetworkListTestState(NetworkListTestPredicate.NetworkListTestStates.VerifyData);
yield return WaitForConditionOrTimeOut(m_NetworkListPredicateHandler);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(m_NetworkListPredicateHandler));
}
[UnityTest]
public IEnumerator NetworkListClear([Values(true, false)] bool useHost)
[Test]
public void NetworkListClear([Values(true, false)] bool useHost)
{
// Re-use the NetworkListAdd to initialize the server and client as well as make sure the list is populated
yield return NetworkListAdd(useHost);
NetworkListAdd(useHost);
m_Player1OnServer.TheList.Clear();
// Verify the element count and values on the client matches the server
m_NetworkListPredicateHandler.SetNetworkListTestState(NetworkListTestPredicate.NetworkListTestStates.VerifyData);
yield return WaitForConditionOrTimeOut(m_NetworkListPredicateHandler);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(m_NetworkListPredicateHandler));
}
[UnityTest]
public IEnumerator TestNetworkVariableClass([Values(true, false)] bool useHost)
[Test]
public void TestNetworkVariableClass([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
bool VerifyClass()
{
@@ -812,13 +834,13 @@ namespace Unity.Netcode.RuntimeTests
m_Player1OnServer.TheClass.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(VerifyClass);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyClass));
}
[UnityTest]
public IEnumerator TestNetworkVariableTemplateClass([Values(true, false)] bool useHost)
[Test]
public void TestNetworkVariableTemplateClass([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
bool VerifyClass()
{
@@ -830,13 +852,13 @@ namespace Unity.Netcode.RuntimeTests
m_Player1OnServer.TheTemplateClass.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(VerifyClass);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyClass));
}
[UnityTest]
public IEnumerator TestNetworkListStruct([Values(true, false)] bool useHost)
[Test]
public void TestNetworkListStruct([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
bool VerifyList()
{
@@ -850,13 +872,13 @@ namespace Unity.Netcode.RuntimeTests
m_Player1OnServer.TheStructList.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(VerifyList);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyList));
}
[UnityTest]
public IEnumerator TestNetworkVariableStruct([Values(true, false)] bool useHost)
[Test]
public void TestNetworkVariableStruct([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
bool VerifyStructure()
{
@@ -868,13 +890,13 @@ namespace Unity.Netcode.RuntimeTests
m_Player1OnServer.TheStruct.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(VerifyStructure);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyStructure));
}
[UnityTest]
public IEnumerator TestNetworkVariableTemplateStruct([Values(true, false)] bool useHost)
[Test]
public void TestNetworkVariableTemplateStruct([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
bool VerifyStructure()
{
@@ -886,13 +908,13 @@ namespace Unity.Netcode.RuntimeTests
m_Player1OnServer.TheTemplateStruct.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(VerifyStructure);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyStructure));
}
[UnityTest]
public IEnumerator TestNetworkVariableTemplateBehaviourClass([Values(true, false)] bool useHost)
[Test]
public void TestNetworkVariableTemplateBehaviourClass([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
bool VerifyClass()
{
@@ -904,13 +926,13 @@ namespace Unity.Netcode.RuntimeTests
m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour>().TheVar.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(VerifyClass);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyClass));
}
[UnityTest]
public IEnumerator TestNetworkVariableTemplateBehaviourClassNotReferencedElsewhere([Values(true, false)] bool useHost)
[Test]
public void TestNetworkVariableTemplateBehaviourClassNotReferencedElsewhere([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
bool VerifyClass()
{
@@ -922,13 +944,13 @@ namespace Unity.Netcode.RuntimeTests
m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(VerifyClass);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyClass));
}
[UnityTest]
public IEnumerator TestNetworkVariableTemplateBehaviourStruct([Values(true, false)] bool useHost)
[Test]
public void TestNetworkVariableTemplateBehaviourStruct([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
bool VerifyClass()
{
@@ -940,13 +962,13 @@ namespace Unity.Netcode.RuntimeTests
m_Player1OnServer.GetComponent<StructHavingNetworkBehaviour>().TheVar.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(VerifyClass);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyClass));
}
[UnityTest]
public IEnumerator TestNetworkVariableEnum([Values(true, false)] bool useHost)
[Test]
public void TestNetworkVariableEnum([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
bool VerifyStructure()
{
@@ -957,13 +979,13 @@ namespace Unity.Netcode.RuntimeTests
m_Player1OnServer.TheEnum.SetDirty(true);
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(VerifyStructure);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyStructure));
}
[UnityTest]
public IEnumerator TestINetworkSerializableClassCallsNetworkSerialize([Values(true, false)] bool useHost)
[Test]
public void TestINetworkSerializableClassCallsNetworkSerialize([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
TestClass.NetworkSerializeCalledOnWrite = false;
TestClass.NetworkSerializeCalledOnRead = false;
m_Player1OnServer.TheClass.Value = new TestClass
@@ -975,13 +997,13 @@ namespace Unity.Netcode.RuntimeTests
static bool VerifyCallback() => TestClass.NetworkSerializeCalledOnWrite && TestClass.NetworkSerializeCalledOnRead;
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(VerifyCallback);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyCallback));
}
[UnityTest]
public IEnumerator TestINetworkSerializableStructCallsNetworkSerialize([Values(true, false)] bool useHost)
[Test]
public void TestINetworkSerializableStructCallsNetworkSerialize([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
TestStruct.NetworkSerializeCalledOnWrite = false;
TestStruct.NetworkSerializeCalledOnRead = false;
m_Player1OnServer.TheStruct.Value = new TestStruct() { SomeInt = k_TestUInt, SomeBool = false };
@@ -989,24 +1011,23 @@ namespace Unity.Netcode.RuntimeTests
static bool VerifyCallback() => TestStruct.NetworkSerializeCalledOnWrite && TestStruct.NetworkSerializeCalledOnRead;
// Wait for the client-side to notify it is finished initializing and spawning.
yield return WaitForConditionOrTimeOut(VerifyCallback);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyCallback));
}
#region COULD_BE_REMOVED
[UnityTest]
[Test]
[Ignore("This is used several times already in the NetworkListPredicate")]
// TODO: If we end up using the new suggested pattern, then delete this
public IEnumerator NetworkListArrayOperator([Values(true, false)] bool useHost)
public void NetworkListArrayOperator([Values(true, false)] bool useHost)
{
yield return NetworkListAdd(useHost);
NetworkListAdd(useHost);
}
[UnityTest]
[Test]
[Ignore("This is used several times already in the NetworkListPredicate")]
// TODO: If we end up using the new suggested pattern, then delete this
public IEnumerator NetworkListIEnumerator([Values(true, false)] bool useHost)
public void NetworkListIEnumerator([Values(true, false)] bool useHost)
{
yield return InitializeServerAndClients(useHost);
InitializeServerAndClients(useHost);
var correctVals = new int[3];
correctVals[0] = k_TestVal1;
correctVals[1] = k_TestVal2;
@@ -1096,6 +1117,21 @@ namespace Unity.Netcode.RuntimeTests
});
}
[Test]
public void TestTypesReferencedInSubclassSerializeSuccessfully()
{
var variable = new NetworkVariableSubclass<TemplatedValueOnlyReferencedByNetworkVariableSubclass<int>>();
using var writer = new FastBufferWriter(1024, Allocator.Temp);
var value = new TemplatedValueOnlyReferencedByNetworkVariableSubclass<int> { Value = 12345 };
variable.Value = value;
variable.WriteField(writer);
variable.Value = new TemplatedValueOnlyReferencedByNetworkVariableSubclass<int> { Value = 54321 };
using var reader = new FastBufferReader(writer, Allocator.None);
variable.ReadField(reader);
Assert.AreEqual(value.Value, variable.Value.Value);
}
[Test]
public void TestUnsupportedUnmanagedTypesWithUserSerializationDoNotThrowExceptions()
{
@@ -1133,12 +1169,14 @@ namespace Unity.Netcode.RuntimeTests
[Test]
public void TestManagedINetworkSerializableNetworkVariablesDeserializeInPlace()
{
var variable = new NetworkVariable<ManagedNetworkSerializableType>();
variable.Value = new ManagedNetworkSerializableType
var variable = new NetworkVariable<ManagedNetworkSerializableType>
{
InMemoryValue = 1,
Ints = new[] { 2, 3, 4 },
Str = "five"
Value = new ManagedNetworkSerializableType
{
InMemoryValue = 1,
Ints = new[] { 2, 3, 4 },
Str = "five"
}
};
using var writer = new FastBufferWriter(1024, Allocator.Temp);
@@ -1163,12 +1201,14 @@ namespace Unity.Netcode.RuntimeTests
[Test]
public void TestUnmnagedINetworkSerializableNetworkVariablesDeserializeInPlace()
{
var variable = new NetworkVariable<UnmanagedNetworkSerializableType>();
variable.Value = new UnmanagedNetworkSerializableType
var variable = new NetworkVariable<UnmanagedNetworkSerializableType>
{
InMemoryValue = 1,
Int = 2,
Str = "three"
Value = new UnmanagedNetworkSerializableType
{
InMemoryValue = 1,
Int = 2,
Str = "three"
}
};
using var writer = new FastBufferWriter(1024, Allocator.Temp);
variable.WriteField(writer);
@@ -1188,7 +1228,6 @@ namespace Unity.Netcode.RuntimeTests
Assert.AreEqual(2, variable.Value.Int, "Int was not correctly deserialized");
Assert.AreEqual("three", variable.Value.Str, "Str was not correctly deserialized");
}
#endregion
private float m_OriginalTimeScale = 1.0f;
@@ -1377,4 +1416,144 @@ namespace Unity.Netcode.RuntimeTests
}
}
}
[TestFixtureSource(nameof(TestDataSource))]
public class NetworkVariableInheritanceTests : NetcodeIntegrationTest
{
public NetworkVariableInheritanceTests(HostOrServer hostOrServer)
: base(hostOrServer)
{
}
protected override int NumberOfClients => 2;
public static IEnumerable<TestFixtureData> TestDataSource() =>
Enum.GetValues(typeof(HostOrServer)).OfType<HostOrServer>().Select(x => new TestFixtureData(x));
public class ComponentA : NetworkBehaviour
{
public NetworkVariable<int> PublicFieldA = new NetworkVariable<int>(1);
protected NetworkVariable<int> m_ProtectedFieldA = new NetworkVariable<int>(2);
private NetworkVariable<int> m_PrivateFieldA = new NetworkVariable<int>(3);
public void ChangeValuesA(int pub, int pro, int pri)
{
PublicFieldA.Value = pub;
m_ProtectedFieldA.Value = pro;
m_PrivateFieldA.Value = pri;
}
public bool CompareValuesA(ComponentA other)
{
return PublicFieldA.Value == other.PublicFieldA.Value &&
m_ProtectedFieldA.Value == other.m_ProtectedFieldA.Value &&
m_PrivateFieldA.Value == other.m_PrivateFieldA.Value;
}
}
public class ComponentB : ComponentA
{
public NetworkVariable<int> PublicFieldB = new NetworkVariable<int>(11);
protected NetworkVariable<int> m_ProtectedFieldB = new NetworkVariable<int>(22);
private NetworkVariable<int> m_PrivateFieldB = new NetworkVariable<int>(33);
public void ChangeValuesB(int pub, int pro, int pri)
{
PublicFieldB.Value = pub;
m_ProtectedFieldB.Value = pro;
m_PrivateFieldB.Value = pri;
}
public bool CompareValuesB(ComponentB other)
{
return PublicFieldB.Value == other.PublicFieldB.Value &&
m_ProtectedFieldB.Value == other.m_ProtectedFieldB.Value &&
m_PrivateFieldB.Value == other.m_PrivateFieldB.Value;
}
}
public class ComponentC : ComponentB
{
public NetworkVariable<int> PublicFieldC = new NetworkVariable<int>(111);
protected NetworkVariable<int> m_ProtectedFieldC = new NetworkVariable<int>(222);
private NetworkVariable<int> m_PrivateFieldC = new NetworkVariable<int>(333);
public void ChangeValuesC(int pub, int pro, int pri)
{
PublicFieldC.Value = pub;
m_ProtectedFieldA.Value = pro;
m_PrivateFieldC.Value = pri;
}
public bool CompareValuesC(ComponentC other)
{
return PublicFieldC.Value == other.PublicFieldC.Value &&
m_ProtectedFieldC.Value == other.m_ProtectedFieldC.Value &&
m_PrivateFieldC.Value == other.m_PrivateFieldC.Value;
}
}
private GameObject m_TestObjectPrefab;
private ulong m_TestObjectId = 0;
protected override void OnServerAndClientsCreated()
{
m_TestObjectPrefab = CreateNetworkObjectPrefab($"[{nameof(NetworkVariableInheritanceTests)}.{nameof(m_TestObjectPrefab)}]");
m_TestObjectPrefab.AddComponent<ComponentA>();
m_TestObjectPrefab.AddComponent<ComponentB>();
m_TestObjectPrefab.AddComponent<ComponentC>();
}
protected override IEnumerator OnServerAndClientsConnected()
{
var serverTestObject = SpawnObject(m_TestObjectPrefab, m_ServerNetworkManager).GetComponent<NetworkObject>();
m_TestObjectId = serverTestObject.NetworkObjectId;
var serverTestComponentA = serverTestObject.GetComponent<ComponentA>();
var serverTestComponentB = serverTestObject.GetComponent<ComponentB>();
var serverTestComponentC = serverTestObject.GetComponent<ComponentC>();
serverTestComponentA.ChangeValuesA(1000, 2000, 3000);
serverTestComponentB.ChangeValuesA(1000, 2000, 3000);
serverTestComponentB.ChangeValuesB(1100, 2200, 3300);
serverTestComponentC.ChangeValuesA(1000, 2000, 3000);
serverTestComponentC.ChangeValuesB(1100, 2200, 3300);
serverTestComponentC.ChangeValuesC(1110, 2220, 3330);
yield return WaitForTicks(m_ServerNetworkManager, 2);
}
private bool CheckTestObjectComponentValuesOnAll()
{
var serverTestObject = m_ServerNetworkManager.SpawnManager.SpawnedObjects[m_TestObjectId];
var serverTestComponentA = serverTestObject.GetComponent<ComponentA>();
var serverTestComponentB = serverTestObject.GetComponent<ComponentB>();
var serverTestComponentC = serverTestObject.GetComponent<ComponentC>();
foreach (var clientNetworkManager in m_ClientNetworkManagers)
{
var clientTestObject = clientNetworkManager.SpawnManager.SpawnedObjects[m_TestObjectId];
var clientTestComponentA = clientTestObject.GetComponent<ComponentA>();
var clientTestComponentB = clientTestObject.GetComponent<ComponentB>();
var clientTestComponentC = clientTestObject.GetComponent<ComponentC>();
if (!serverTestComponentA.CompareValuesA(clientTestComponentA) ||
!serverTestComponentB.CompareValuesA(clientTestComponentB) ||
!serverTestComponentB.CompareValuesB(clientTestComponentB) ||
!serverTestComponentC.CompareValuesA(clientTestComponentC) ||
!serverTestComponentC.CompareValuesB(clientTestComponentC) ||
!serverTestComponentC.CompareValuesC(clientTestComponentC))
{
return false;
}
}
return true;
}
[UnityTest]
public IEnumerator TestInheritedFields()
{
yield return WaitForConditionOrTimeOut(CheckTestObjectComponentValuesOnAll);
Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, nameof(CheckTestObjectComponentValuesOnAll));
}
}
}