This repository has been archived on 2025-04-22. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
com.unity.netcode.gameobjects/Tests/Runtime/Serialization/NetworkObjectReferenceTests.cs
Unity Technologies 63c7e4c78a com.unity.netcode.gameobjects@2.0.0-exp.4
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).

## [2.0.0-exp.4] - 2024-05-31

### Added

- Added `NetworkRigidbodyBase.AttachToFixedJoint` and `NetworkRigidbodyBase.DetachFromFixedJoint` to replace parenting for rigid bodies that have `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled. (#2933)
- 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 non-authoritative rigid bodies with `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled would constantly log errors about the renderTime being before `StartTimeConsumed`. (#2933)
- Fixed issue where in-scene placed NetworkObjects could be destroyed if a client disconnects early and/or before approval. (#2924)
- 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

- Change all the access modifiers of test class from Public to Internal (#2930)
- Changed messages are now sorted by enum values as opposed to ordinally sorting the messages by their type name. (#2929)
- Changed `NetworkClient.SessionModeTypes` to `NetworkClient.NetworkTopologyTypes`. (#2875)
- Changed `NetworkClient.SessionModeType` to `NetworkClient.NetworkTopologyType`. (#2875)
- Changed `NetworkConfig.SessionMode` to `NeworkConfig.NetworkTopology`. (#2875)
2024-05-31 00:00:00 +00:00

384 lines
14 KiB
C#

using System;
using System.Collections;
using NUnit.Framework;
using Unity.Collections;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using UnityEngine.TestTools;
using Object = UnityEngine.Object;
namespace Unity.Netcode.RuntimeTests
{
/// <summary>
/// Unit tests to test:
/// - Serializing NetworkObject to NetworkObjectReference
/// - Deserializing NetworkObjectReference to NetworkObject
/// - Implicit operators of NetworkObjectReference
/// </summary>
internal class NetworkObjectReferenceTests : IDisposable
{
private class TestNetworkBehaviour : NetworkBehaviour
{
public NetworkVariable<NetworkObjectReference> TestVariable = new NetworkVariable<NetworkObjectReference>();
public NetworkObject RpcReceivedNetworkObject;
public GameObject RpcReceivedGameObject;
[ServerRpc]
public void SendReferenceServerRpc(NetworkObjectReference value)
{
RpcReceivedGameObject = value;
RpcReceivedNetworkObject = value;
}
}
[Test]
public void TestSerializeNetworkObject()
{
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
networkObjectContext.Object.Spawn();
var outWriter = new FastBufferWriter(1300, Allocator.Temp);
try
{
// serialize
var outSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(outWriter));
NetworkObjectReference outReference = networkObjectContext.Object;
outReference.NetworkSerialize(outSerializer);
// deserialize
NetworkObjectReference inReference = default;
var inReader = new FastBufferReader(outWriter, Allocator.Temp);
try
{
var inSerializer =
new BufferSerializer<BufferSerializerReader>(new BufferSerializerReader(inReader));
inReference.NetworkSerialize(inSerializer);
}
finally
{
inReader.Dispose();
}
// validate
Assert.NotNull((NetworkObject)inReference);
Assert.AreEqual(inReference.NetworkObjectId, networkObjectContext.Object.NetworkObjectId);
Assert.AreEqual(outReference, inReference);
Assert.AreEqual(networkObjectContext.Object, (NetworkObject)inReference);
}
finally
{
outWriter.Dispose();
}
}
[Test]
public void TestSerializeGameObject()
{
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
networkObjectContext.Object.Spawn();
var outWriter = new FastBufferWriter(1300, Allocator.Temp);
try
{
// serialize
var outSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(outWriter));
NetworkObjectReference outReference = networkObjectContext.Object.gameObject;
outReference.NetworkSerialize(outSerializer);
// deserialize
NetworkObjectReference inReference = default;
var inReader = new FastBufferReader(outWriter, Allocator.Temp);
try
{
var inSerializer =
new BufferSerializer<BufferSerializerReader>(new BufferSerializerReader(inReader));
inReference.NetworkSerialize(inSerializer);
}
finally
{
inReader.Dispose();
}
GameObject gameObject = inReference;
// validate
Assert.AreEqual(outReference, inReference);
Assert.AreEqual(networkObjectContext.Object.gameObject, gameObject);
}
finally
{
outWriter.Dispose();
}
}
[Test]
public void TestImplicitConversionToGameObject()
{
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
networkObjectContext.Object.Spawn();
NetworkObjectReference outReference = networkObjectContext.Object.gameObject;
GameObject go = outReference;
Assert.AreEqual(networkObjectContext.Object.gameObject, go);
}
[Test]
public void TestImplicitToGameObjectIsNullWhenNotFound()
{
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
networkObjectContext.Object.Spawn();
NetworkObjectReference outReference = networkObjectContext.Object.gameObject;
networkObjectContext.Object.Despawn();
Object.DestroyImmediate(networkObjectContext.Object.gameObject);
GameObject go = outReference;
Assert.IsNull(go);
}
[Test]
public void TestTryGet()
{
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
networkObjectContext.Object.Spawn();
NetworkObjectReference networkObjectReference = networkObjectContext.Object;
Assert.True(networkObjectReference.TryGet(out NetworkObject networkObject));
Assert.NotNull(networkObject);
networkObjectReference.TryGet(out NetworkObject result);
Assert.AreEqual(networkObject, result);
}
[UnityTest]
public IEnumerator TestRpc()
{
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
var testNetworkBehaviour = networkObjectContext.Object.gameObject.AddComponent<TestNetworkBehaviour>();
networkObjectContext.Object.Spawn();
using var otherObjectContext = UnityObjectContext.CreateNetworkObject();
otherObjectContext.Object.Spawn();
testNetworkBehaviour.SendReferenceServerRpc(new NetworkObjectReference(otherObjectContext.Object));
// wait for rpc completion
float t = 0;
while (testNetworkBehaviour.RpcReceivedGameObject == null)
{
t += Time.deltaTime;
if (t > 5f)
{
new AssertionException("RPC with NetworkBehaviour reference hasn't been received");
}
yield return null;
}
// validate
Assert.AreEqual(otherObjectContext.Object, testNetworkBehaviour.RpcReceivedNetworkObject);
Assert.AreEqual(otherObjectContext.Object.gameObject, testNetworkBehaviour.RpcReceivedGameObject);
}
[UnityTest]
public IEnumerator TestRpcImplicitNetworkObject()
{
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
var testNetworkBehaviour = networkObjectContext.Object.gameObject.AddComponent<TestNetworkBehaviour>();
networkObjectContext.Object.Spawn();
using var otherObjectContext = UnityObjectContext.CreateNetworkObject();
otherObjectContext.Object.Spawn();
testNetworkBehaviour.SendReferenceServerRpc(otherObjectContext.Object);
// wait for rpc completion
float t = 0;
while (testNetworkBehaviour.RpcReceivedGameObject == null)
{
t += Time.deltaTime;
if (t > 5f)
{
new AssertionException("RPC with NetworkBehaviour reference hasn't been received");
}
yield return null;
}
// validate
Assert.AreEqual(otherObjectContext.Object, testNetworkBehaviour.RpcReceivedNetworkObject);
Assert.AreEqual(otherObjectContext.Object.gameObject, testNetworkBehaviour.RpcReceivedGameObject);
}
[UnityTest]
public IEnumerator TestRpcImplicitGameObject()
{
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
var testNetworkBehaviour = networkObjectContext.Object.gameObject.AddComponent<TestNetworkBehaviour>();
networkObjectContext.Object.Spawn();
using var otherObjectContext = UnityObjectContext.CreateNetworkObject();
otherObjectContext.Object.Spawn();
testNetworkBehaviour.SendReferenceServerRpc(otherObjectContext.Object.gameObject);
// wait for rpc completion
float t = 0;
while (testNetworkBehaviour.RpcReceivedGameObject == null)
{
t += Time.deltaTime;
if (t > 5f)
{
new AssertionException("RPC with NetworkBehaviour reference hasn't been received");
}
yield return null;
}
// validate
Assert.AreEqual(otherObjectContext.Object, testNetworkBehaviour.RpcReceivedNetworkObject);
Assert.AreEqual(otherObjectContext.Object.gameObject, testNetworkBehaviour.RpcReceivedGameObject);
}
[Test]
public void TestNetworkVariable()
{
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
var testNetworkBehaviour = networkObjectContext.Object.gameObject.AddComponent<TestNetworkBehaviour>();
networkObjectContext.Object.Spawn();
using var otherObjectContext = UnityObjectContext.CreateNetworkObject();
otherObjectContext.Object.Spawn();
// check default value is null
Assert.IsNull((NetworkObject)testNetworkBehaviour.TestVariable.Value);
testNetworkBehaviour.TestVariable.Value = networkObjectContext.Object;
Assert.AreEqual((GameObject)testNetworkBehaviour.TestVariable.Value, networkObjectContext.Object.gameObject);
Assert.AreEqual((NetworkObject)testNetworkBehaviour.TestVariable.Value, networkObjectContext.Object);
}
[Test]
public void TestDespawn()
{
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
networkObjectContext.Object.Spawn();
var originalId = networkObjectContext.Object.NetworkObjectId;
NetworkObjectReference networkObjectReference = networkObjectContext.Object;
Assert.AreEqual(networkObjectContext.Object, (NetworkObject)networkObjectReference);
networkObjectContext.Object.Despawn();
Assert.IsFalse(networkObjectReference.TryGet(out NetworkObject _));
networkObjectContext.Object.Spawn();
// After spawning again the reference will still no longer work as it still points to the old object
Assert.AreNotEqual(originalId, networkObjectContext.Object.NetworkObjectId);
Assert.IsFalse(networkObjectReference.TryGet(out NetworkObject _));
// creating a new reference will make it work again
networkObjectReference = networkObjectContext.Object;
Assert.AreEqual(networkObjectContext.Object, (NetworkObject)networkObjectReference);
}
[Test]
public void FailSerializeNonSpawnedNetworkObject()
{
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
Assert.Throws<ArgumentException>(() =>
{
NetworkObjectReference outReference = networkObjectContext.Object;
});
}
[Test]
public void FailSerializeGameObjectWithoutNetworkObject()
{
using var gameObjectContext = UnityObjectContext.CreateGameObject();
Assert.Throws<ArgumentException>(() =>
{
NetworkObjectReference outReference = gameObjectContext.Object;
});
}
[Test]
public void FailSerializeNullNetworkObject()
{
Assert.Throws<ArgumentNullException>(() =>
{
NetworkObjectReference outReference = (NetworkObject)null;
});
}
[Test]
public void FailSerializeNullGameObject()
{
Assert.Throws<ArgumentNullException>(() =>
{
NetworkObjectReference outReference = (GameObject)null;
});
}
public void Dispose()
{
//Stop, shutdown, and destroy
NetworkManagerHelper.ShutdownNetworkManager();
}
public NetworkObjectReferenceTests()
{
//Create, instantiate, and host
NetworkManagerHelper.StartNetworkManager(out _);
}
}
/// <summary>
/// Helper method for tests to create and destroy Unity Objects.
/// </summary>
/// <typeparam name="T">The type of Object this context incorporates.</typeparam>
internal class UnityObjectContext<T> : UnityObjectContext where T : Object
{
private T m_Object;
internal UnityObjectContext(T unityObject, Object root)
: base(root)
{
m_Object = unityObject;
}
public T Object => m_Object;
}
internal class UnityObjectContext : IDisposable
{
private Object m_Root;
protected UnityObjectContext(Object root)
{
m_Root = root;
}
public static UnityObjectContext<GameObject> CreateGameObject(string name = "")
{
var gameObject = new GameObject(name);
return new UnityObjectContext<GameObject>(gameObject, gameObject);
}
public static UnityObjectContext<NetworkObject> CreateNetworkObject(string name = "")
{
var gameObject = new GameObject(name);
var networkObject = gameObject.AddComponent<NetworkObject>();
return new UnityObjectContext<NetworkObject>(networkObject, gameObject);
}
public void Dispose()
{
Object.DestroyImmediate(m_Root);
}
}
}