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/RpcTests.cs
Unity Technologies 07f206ff9e com.unity.netcode.gameobjects@1.8.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.8.0] - 2023-12-12

### Added

- Added a new RPC attribute, which is simply `Rpc`. (#2762)
  - This is a generic attribute that can perform the functions of both Server and Client RPCs, as well as enabling client-to-client RPCs. Includes several default targets: `Server`, `NotServer`, `Owner`, `NotOwner`, `Me`, `NotMe`, `ClientsAndHost`, and `Everyone`. Runtime overrides are available for any of these targets, as well as for sending to a specific ID or groups of IDs.
  - This attribute also includes the ability to defer RPCs that are sent to the local process to the start of the next frame instead of executing them immediately, treating them as if they had gone across the network. The default behavior is to execute immediately.
  - This attribute effectively replaces `ServerRpc` and `ClientRpc`. `ServerRpc` and `ClientRpc` remain in their existing forms for backward compatibility, but `Rpc` will be the recommended and most supported option.
- Added `NetworkManager.OnConnectionEvent` as a unified connection event callback to notify clients and servers of all client connections and disconnections within the session (#2762)
- Added `NetworkManager.ServerIsHost` and `NetworkBehaviour.ServerIsHost` to allow a client to tell if it is connected to a host or to a dedicated server (#2762)
- Added `SceneEventProgress.SceneManagementNotEnabled` return status to be returned when a `NetworkSceneManager` method is invoked and scene management is not enabled. (#2735)
- Added `SceneEventProgress.ServerOnlyAction` return status to be returned when a `NetworkSceneManager` method is invoked by a client. (#2735)
- Added `NetworkObject.InstantiateAndSpawn` and `NetworkSpawnManager.InstantiateAndSpawn` methods to simplify prefab spawning by assuring that the prefab is valid and applies any override prior to instantiating the `GameObject` and spawning the `NetworkObject` instance. (#2710)

### Fixed

- Fixed issue where a client disconnected by a server-host would not receive a local notification. (#2789)
- Fixed issue where a server-host could shutdown during a relay connection but periodically the transport disconnect message sent to any connected clients could be dropped. (#2789)
- Fixed issue where a host could disconnect its local client but remain running as a server. (#2789)
- Fixed issue where `OnClientDisconnectedCallback` was not being invoked under certain conditions. (#2789)
- Fixed issue where `OnClientDisconnectedCallback` was always returning 0 as the client identifier. (#2789)
- Fixed issue where if a host or server shutdown while a client owned NetworkObjects (other than the player) it would throw an exception. (#2789)
- Fixed issue where setting values on a `NetworkVariable` or `NetworkList` within `OnNetworkDespawn` during a shutdown sequence would throw an exception. (#2789)
- Fixed issue where a teleport state could potentially be overridden by a previous unreliable delta state. (#2777)
- Fixed issue where `NetworkTransform` was using the `NetworkManager.ServerTime.Tick` as opposed to `NetworkManager.NetworkTickSystem.ServerTime.Tick` during the authoritative side's tick update where it performed a delta state check. (#2777)
- Fixed issue where a parented in-scene placed NetworkObject would be destroyed upon a client or server exiting a network session but not unloading the original scene in which the NetworkObject was placed. (#2737)
- Fixed issue where during client synchronization and scene loading, when client synchronization or the scene loading mode are set to `LoadSceneMode.Single`, a `CreateObjectMessage` could be received, processed, and the resultant spawned `NetworkObject` could be instantiated in the client's currently active scene that could, towards the end of the client synchronization or loading process, be unloaded and cause the newly created `NetworkObject` to be destroyed (and throw and exception). (#2735)
- Fixed issue where a `NetworkTransform` instance with interpolation enabled would result in wide visual motion gaps (stuttering) under above normal latency conditions and a 1-5% or higher packet are drop rate. (#2713)
- Fixed issue where  you could not have multiple source network prefab overrides targeting the same network prefab as their override. (#2710)

### Changed
- Changed the server or host shutdown so it will now perform a "soft shutdown" when `NetworkManager.Shutdown` is invoked. This will send a disconnect notification to all connected clients and the server-host will wait for all connected clients to disconnect or timeout after a 5 second period before completing the shutdown process. (#2789)
- Changed `OnClientDisconnectedCallback` will now return the assigned client identifier on the local client side if the client was approved and assigned one prior to being disconnected. (#2789)
- Changed `NetworkTransform.SetState` (and related methods) now are cumulative during a fractional tick period and sent on the next pending tick. (#2777)
- `NetworkManager.ConnectedClientsIds` is now accessible on the client side and will contain the list of all clients in the session, including the host client if the server is operating in host mode (#2762)
- Changed `NetworkSceneManager` to return a `SceneEventProgress` status and not throw exceptions for methods invoked when scene management is disabled and when a client attempts to access a `NetworkSceneManager` method by a client. (#2735)
- Changed `NetworkTransform` authoritative instance tick registration so a single `NetworkTransform` specific tick event update will update all authoritative instances to improve perofmance. (#2713)
- Changed `NetworkPrefabs.OverrideToNetworkPrefab` dictionary is no longer used/populated due to it ending up being related to a regression bug and not allowing more than one override to be assigned to a network prefab asset. (#2710)
- Changed in-scene placed `NetworkObject`s now store their source network prefab asset's `GlobalObjectIdHash` internally that is used, when scene management is disabled, by clients to spawn the correct prefab even if the `NetworkPrefab` entry has an override. This does not impact dynamically spawning the same prefab which will yield the override on both host and client. (#2710)
- Changed in-scene placed `NetworkObject`s no longer require a `NetworkPrefab` entry with `GlobalObjectIdHash` override in order for clients to properly synchronize. (#2710)
- Changed in-scene placed `NetworkObject`s now set their `IsSceneObject` value when generating their `GlobalObjectIdHash` value. (#2710)
- Changed the default `NetworkConfig.SpawnTimeout` value from 1.0s to 10.0s. (#2710)
2023-12-12 00:00:00 +00:00

230 lines
9.0 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using Unity.Collections;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine.TestTools;
using Debug = UnityEngine.Debug;
using Vector3 = UnityEngine.Vector3;
namespace Unity.Netcode.RuntimeTests
{
public class RpcTests : NetcodeIntegrationTest
{
public class CompileTimeNoRpcsBaseClassTest : NetworkBehaviour
{
}
public class CompileTimeHasRpcsChildClassDerivedFromNoRpcsBaseClassTest : CompileTimeNoRpcsBaseClassTest
{
[ServerRpc]
public void SomeDummyServerRpc()
{
}
}
public class GenericRpcTestNB<T> : NetworkBehaviour where T : unmanaged
{
public event Action<T, ServerRpcParams> OnServer_Rpc;
[ServerRpc]
public void MyServerRpc(T clientId, ServerRpcParams param = default)
{
OnServer_Rpc(clientId, param);
}
}
public class RpcTestNBFloat : GenericRpcTestNB<float>
{
}
public class RpcTestNB : GenericRpcTestNB<ulong>
{
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
public event Action<NativeList<ulong>, ServerRpcParams> OnNativeListServer_Rpc;
#endif
public event Action<Vector3, Vector3[],
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
NativeList<Vector3>,
#endif
FixedString32Bytes> OnTypedServer_Rpc;
public event Action OnClient_Rpc;
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
[ServerRpc]
public void MyNativeListServerRpc(NativeList<ulong> clientId, ServerRpcParams param = default)
{
OnNativeListServer_Rpc(clientId, param);
}
#endif
[ClientRpc]
public void MyClientRpc()
{
OnClient_Rpc();
}
[ServerRpc]
public void MyTypedServerRpc(Vector3 param1, Vector3[] param2,
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
NativeList<Vector3> param3,
#endif
FixedString32Bytes param4)
{
OnTypedServer_Rpc(param1, param2,
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
param3,
#endif
param4);
}
}
protected override int NumberOfClients => 1;
protected override void OnCreatePlayerPrefab()
{
m_PlayerPrefab.AddComponent<RpcTestNB>();
m_PlayerPrefab.AddComponent<RpcTestNBFloat>();
}
[UnityTest]
public IEnumerator TestRpcs()
{
// This is the *SERVER VERSION* of the *CLIENT PLAYER* RpcTestNB component
var serverClientRpcTestNB = m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId][m_ClientNetworkManagers[0].LocalClientId].GetComponent<RpcTestNB>();
var serverClientRpcTestNBFloat = m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId][m_ClientNetworkManagers[0].LocalClientId].GetComponent<RpcTestNBFloat>();
// This is the *CLIENT VERSION* of the *CLIENT PLAYER* RpcTestNB component
var localClienRpcTestNB = m_PlayerNetworkObjects[m_ClientNetworkManagers[0].LocalClientId][m_ClientNetworkManagers[0].LocalClientId].GetComponent<RpcTestNB>();
var localClienRpcTestNBFloat = m_PlayerNetworkObjects[m_ClientNetworkManagers[0].LocalClientId][m_ClientNetworkManagers[0].LocalClientId].GetComponent<RpcTestNBFloat>();
// Setup state
bool hasReceivedServerRpc = false;
bool hasReceivedFloatServerRpc = false;
bool hasReceivedTypedServerRpc = false;
bool hasReceivedClientRpcRemotely = false;
bool hasReceivedClientRpcLocally = false;
var vector3 = new Vector3(1, 2, 3);
Vector3[] vector3s = new[] { new Vector3(4, 5, 6), new Vector3(7, 8, 9) };
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
using var vector3sNativeList = new NativeList<Vector3>(Allocator.Persistent)
{
new Vector3(10, 11, 12),
new Vector3(13, 14, 15)
};
#endif
localClienRpcTestNB.OnClient_Rpc += () =>
{
Debug.Log("ClientRpc received on client object");
hasReceivedClientRpcRemotely = true;
};
localClienRpcTestNB.OnServer_Rpc += (clientId, param) =>
{
// The RPC invoked locally. (Weaver failure?)
Assert.Fail("ServerRpc invoked locally. Weaver failure?");
};
localClienRpcTestNBFloat.OnServer_Rpc += (clientId, param) =>
{
// The RPC invoked locally. (Weaver failure?)
Assert.Fail("ServerRpc (float) invoked locally. Weaver failure?");
};
serverClientRpcTestNB.OnServer_Rpc += (clientId, param) =>
{
Debug.Log("ServerRpc received on server object");
Assert.True(param.Receive.SenderClientId == clientId);
hasReceivedServerRpc = true;
};
serverClientRpcTestNBFloat.OnServer_Rpc += (clientId, param) =>
{
Debug.Log("ServerRpc (float) received on server object");
Assert.True(param.Receive.SenderClientId == clientId);
hasReceivedFloatServerRpc = true;
};
serverClientRpcTestNB.OnClient_Rpc += () =>
{
// The RPC invoked locally. (Weaver failure?)
Debug.Log("ClientRpc received on server object");
hasReceivedClientRpcLocally = true;
};
var str = new FixedString32Bytes("abcdefg");
serverClientRpcTestNB.OnTypedServer_Rpc += (param1, param2,
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
param3,
#endif
param4) =>
{
Debug.Log("TypedServerRpc received on server object");
Assert.AreEqual(param1, vector3);
Assert.AreEqual(param2.Length, vector3s.Length);
Assert.AreEqual(param2[0], vector3s[0]);
Assert.AreEqual(param2[1], vector3s[1]);
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
Assert.AreEqual(param3.Length, vector3s.Length);
Assert.AreEqual(param3[0], vector3sNativeList[0]);
Assert.AreEqual(param3[1], vector3sNativeList[1]);
#endif
Assert.AreEqual(param4, str);
hasReceivedTypedServerRpc = true;
};
// Send ServerRpc
localClienRpcTestNB.MyServerRpc(m_ClientNetworkManagers[0].LocalClientId);
localClienRpcTestNBFloat.MyServerRpc(m_ClientNetworkManagers[0].LocalClientId);
// Send TypedServerRpc
localClienRpcTestNB.MyTypedServerRpc(vector3, vector3s,
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
vector3sNativeList,
#endif
str);
// Send ClientRpc
serverClientRpcTestNB.MyClientRpc();
// Validate each NetworkManager relative NetworkMessageManager received each respective RPC
var messageHookList = new List<MessageHookEntry>();
var serverMessageHookEntry = new MessageHookEntry(m_ServerNetworkManager);
serverMessageHookEntry.AssignMessageType<ServerRpcMessage>();
messageHookList.Add(serverMessageHookEntry);
var typedServerMessageHookEntry = new MessageHookEntry(m_ServerNetworkManager);
typedServerMessageHookEntry.AssignMessageType<ServerRpcMessage>();
messageHookList.Add(typedServerMessageHookEntry);
foreach (var client in m_ClientNetworkManagers)
{
var clientMessageHookEntry = new MessageHookEntry(client);
clientMessageHookEntry.AssignMessageType<ClientRpcMessage>();
messageHookList.Add(clientMessageHookEntry);
}
var rpcMessageHooks = new MessageHooksConditional(messageHookList);
yield return WaitForConditionOrTimeOut(rpcMessageHooks);
Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for messages: {rpcMessageHooks.GetHooksStillWaiting()}");
// Make sure RPCs propagated all the way up and were called on the relative destination class instance
yield return WaitForConditionOrTimeOut(() => hasReceivedServerRpc && hasReceivedClientRpcLocally && hasReceivedClientRpcRemotely && hasReceivedTypedServerRpc);
Assert.True(hasReceivedServerRpc, "ServerRpc was not received");
Assert.True(hasReceivedFloatServerRpc, "ServerRpc was not received");
Assert.True(hasReceivedTypedServerRpc, "TypedServerRpc was not received");
Assert.True(hasReceivedClientRpcLocally, "ClientRpc was not locally received on the server");
Assert.True(hasReceivedClientRpcRemotely, "ClientRpc was not remotely received on the client");
}
}
}