Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
896943c8bf |
24
CHANGELOG.md
24
CHANGELOG.md
@@ -5,6 +5,29 @@ All notable changes to this project will be documented in this file.
|
|||||||
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).
|
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).
|
Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
|
||||||
|
## [1.10.0] - 2024-07-22
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Added `NetworkBehaviour.OnNetworkPreSpawn` and `NetworkBehaviour.OnNetworkPostSpawn` methods that provide the ability to handle pre and post spawning actions during the `NetworkObject` spawn sequence. (#2906)
|
||||||
|
- 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. (#2906)
|
||||||
|
- 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. (#2906)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed issue where the realtime network stats monitor was not able to display RPC traffic in release builds due to those stats being only available in development builds or the editor. (#2980)
|
||||||
|
- Fixed issue where `NetworkManager.ScenesLoaded` was not being updated if `PostSynchronizationSceneUnloading` was set and any loaded scenes not used during synchronization were unloaded.(#2977)
|
||||||
|
- Fixed issue where internal delta serialization could not have a byte serializer defined when serializing deltas for other types. Added `[GenerateSerializationForType(typeof(byte))]` to both the `NetworkVariable` and `AnticipatedNetworkVariable` classes to assure a byte serializer is defined. (#2953)
|
||||||
|
- Fixed issue with the client count not being correct on the host or server side when a client disconnects itself from a session. (#2941)
|
||||||
|
- Fixed issue with the host trying to send itself a message that it has connected when first starting up. (#2941)
|
||||||
|
- Fixed issue where in-scene placed NetworkObjects could be destroyed if a client disconnects early and/or before approval. (#2923)
|
||||||
|
- Fixed issue where `NetworkDeltaPosition` would "jitter" periodically if both unreliable delta state updates and half-floats were used together. (#2922)
|
||||||
|
- Fixed issue where `NetworkRigidbody2D` would not properly change body type based on the instance's authority when spawned. (#2916)
|
||||||
|
- 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. (#2906)
|
||||||
|
- 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. (#2895)
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
|
||||||
## [1.9.1] - 2024-04-18
|
## [1.9.1] - 2024-04-18
|
||||||
|
|
||||||
@@ -16,7 +39,6 @@ Additional documentation and release notes are available at [Multiplayer Documen
|
|||||||
- Added virtual method NetworkVariableBase.OnInitialize() which can be used by NetworkVariable subclasses to add initialization code (#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 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)
|
- Added NetworkTime.TickWithPartial, which represents the current tick as a double that includes the fractional/partial tick value. (#2820)
|
||||||
- Added NetworkTickSystem.AnticipationTick, which can be helpful with implementation of client anticipation. This value represents the tick the current local client was at at the beginning of the most recent network round trip, which enables it to correlate server update ticks with the client tick that may have triggered them. (#2820)
|
|
||||||
- `NetworkVariable` now includes built-in support for `NativeHashSet`, `NativeHashMap`, `List`, `HashSet`, and `Dictionary` (#2813)
|
- `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)
|
- `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)
|
- `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)
|
||||||
|
|||||||
@@ -32,9 +32,13 @@ namespace Unity.Netcode.Components
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
|
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
|
||||||
{
|
{
|
||||||
HalfVector3.NetworkSerialize(serializer);
|
if (!SynchronizeBase)
|
||||||
if (SynchronizeBase)
|
|
||||||
{
|
{
|
||||||
|
HalfVector3.NetworkSerialize(serializer);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
serializer.SerializeValue(ref DeltaPosition);
|
||||||
serializer.SerializeValue(ref CurrentBasePosition);
|
serializer.SerializeValue(ref CurrentBasePosition);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,76 +12,101 @@ namespace Unity.Netcode.Components
|
|||||||
[AddComponentMenu("Netcode/Network Rigidbody 2D")]
|
[AddComponentMenu("Netcode/Network Rigidbody 2D")]
|
||||||
public class NetworkRigidbody2D : NetworkBehaviour
|
public class NetworkRigidbody2D : NetworkBehaviour
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Determines if we are server (true) or owner (false) authoritative
|
||||||
|
/// </summary>
|
||||||
|
private bool m_IsServerAuthoritative;
|
||||||
|
|
||||||
private Rigidbody2D m_Rigidbody;
|
private Rigidbody2D m_Rigidbody;
|
||||||
private NetworkTransform m_NetworkTransform;
|
private NetworkTransform m_NetworkTransform;
|
||||||
|
|
||||||
private bool m_OriginalKinematic;
|
|
||||||
private RigidbodyInterpolation2D m_OriginalInterpolation;
|
private RigidbodyInterpolation2D m_OriginalInterpolation;
|
||||||
|
|
||||||
// Used to cache the authority state of this rigidbody during the last frame
|
// Used to cache the authority state of this rigidbody during the last frame
|
||||||
private bool m_IsAuthority;
|
private bool m_IsAuthority;
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets a bool value indicating whether this <see cref="NetworkRigidbody2D"/> on this peer currently holds authority.
|
|
||||||
/// </summary>
|
|
||||||
private bool HasAuthority => m_NetworkTransform.CanCommitToTransform;
|
|
||||||
|
|
||||||
private void Awake()
|
private void Awake()
|
||||||
{
|
{
|
||||||
m_Rigidbody = GetComponent<Rigidbody2D>();
|
|
||||||
m_NetworkTransform = GetComponent<NetworkTransform>();
|
m_NetworkTransform = GetComponent<NetworkTransform>();
|
||||||
|
m_IsServerAuthoritative = m_NetworkTransform.IsServerAuthoritative();
|
||||||
|
|
||||||
|
SetupRigidBody();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// If the current <see cref="NetworkTransform"/> has authority,
|
||||||
|
/// then use the <see cref="Rigidbody2D"/> interpolation strategy,
|
||||||
|
/// if the <see cref="NetworkTransform"/> is handling interpolation,
|
||||||
|
/// set interpolation to none on the <see cref="Rigidbody2D"/>
|
||||||
|
/// <br/>
|
||||||
|
/// Turn off physics for the rigid body until spawned, otherwise
|
||||||
|
/// clients can run fixed update before the first
|
||||||
|
/// full <see cref="NetworkTransform"/> update
|
||||||
|
/// </summary>
|
||||||
|
private void SetupRigidBody()
|
||||||
|
{
|
||||||
|
m_Rigidbody = GetComponent<Rigidbody2D>();
|
||||||
|
m_OriginalInterpolation = m_Rigidbody.interpolation;
|
||||||
|
|
||||||
|
m_Rigidbody.interpolation = m_IsAuthority ? m_OriginalInterpolation : (m_NetworkTransform.Interpolate ? RigidbodyInterpolation2D.None : m_OriginalInterpolation);
|
||||||
// Turn off physics for the rigid body until spawned, otherwise
|
// Turn off physics for the rigid body until spawned, otherwise
|
||||||
// clients can run fixed update before the first full
|
// clients can run fixed update before the first full
|
||||||
// NetworkTransform update
|
// NetworkTransform update
|
||||||
m_Rigidbody.isKinematic = true;
|
m_Rigidbody.isKinematic = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void FixedUpdate()
|
/// <summary>
|
||||||
|
/// For owner authoritative (i.e. ClientNetworkTransform)
|
||||||
|
/// we adjust our authority when we gain ownership
|
||||||
|
/// </summary>
|
||||||
|
public override void OnGainedOwnership()
|
||||||
{
|
{
|
||||||
if (IsSpawned)
|
UpdateOwnershipAuthority();
|
||||||
{
|
|
||||||
if (HasAuthority != m_IsAuthority)
|
|
||||||
{
|
|
||||||
m_IsAuthority = HasAuthority;
|
|
||||||
UpdateRigidbodyKinematicMode();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Puts the rigidbody in a kinematic non-interpolated mode on everyone but the server.
|
/// <summary>
|
||||||
private void UpdateRigidbodyKinematicMode()
|
/// For owner authoritative(i.e. ClientNetworkTransform)
|
||||||
|
/// we adjust our authority when we have lost ownership
|
||||||
|
/// </summary>
|
||||||
|
public override void OnLostOwnership()
|
||||||
{
|
{
|
||||||
if (m_IsAuthority == false)
|
UpdateOwnershipAuthority();
|
||||||
{
|
}
|
||||||
m_OriginalKinematic = m_Rigidbody.isKinematic;
|
|
||||||
m_Rigidbody.isKinematic = true;
|
|
||||||
|
|
||||||
m_OriginalInterpolation = m_Rigidbody.interpolation;
|
/// <summary>
|
||||||
// Set interpolation to none, the NetworkTransform component interpolates the position of the object.
|
/// Sets the authority differently depending upon
|
||||||
m_Rigidbody.interpolation = RigidbodyInterpolation2D.None;
|
/// whether it is server or owner authoritative
|
||||||
|
/// </summary>
|
||||||
|
private void UpdateOwnershipAuthority()
|
||||||
|
{
|
||||||
|
if (m_IsServerAuthoritative)
|
||||||
|
{
|
||||||
|
m_IsAuthority = NetworkManager.IsServer;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Resets the rigidbody back to it's non replication only state. Happens on shutdown and when authority is lost
|
m_IsAuthority = IsOwner;
|
||||||
m_Rigidbody.isKinematic = m_OriginalKinematic;
|
|
||||||
m_Rigidbody.interpolation = m_OriginalInterpolation;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If you have authority then you are not kinematic
|
||||||
|
m_Rigidbody.isKinematic = !m_IsAuthority;
|
||||||
|
|
||||||
|
// Set interpolation of the Rigidbody2D based on authority
|
||||||
|
// With authority: let local transform handle interpolation
|
||||||
|
// Without authority: let the NetworkTransform handle interpolation
|
||||||
|
m_Rigidbody.interpolation = m_IsAuthority ? m_OriginalInterpolation : RigidbodyInterpolation2D.None;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override void OnNetworkSpawn()
|
public override void OnNetworkSpawn()
|
||||||
{
|
{
|
||||||
m_IsAuthority = HasAuthority;
|
UpdateOwnershipAuthority();
|
||||||
m_OriginalKinematic = m_Rigidbody.isKinematic;
|
|
||||||
m_OriginalInterpolation = m_Rigidbody.interpolation;
|
|
||||||
UpdateRigidbodyKinematicMode();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override void OnNetworkDespawn()
|
public override void OnNetworkDespawn()
|
||||||
{
|
{
|
||||||
UpdateRigidbodyKinematicMode();
|
UpdateOwnershipAuthority();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1682,6 +1682,15 @@ namespace Unity.Netcode.Components
|
|||||||
var scale = transformToUse.localScale;
|
var scale = transformToUse.localScale;
|
||||||
networkState.IsSynchronizing = isSynchronization;
|
networkState.IsSynchronizing = isSynchronization;
|
||||||
|
|
||||||
|
// All of the checks below, up to the delta position checking portion, are to determine if the
|
||||||
|
// authority changed a property during runtime that requires a full synchronizing.
|
||||||
|
if (InLocalSpace != networkState.InLocalSpace)
|
||||||
|
{
|
||||||
|
networkState.InLocalSpace = InLocalSpace;
|
||||||
|
isDirty = true;
|
||||||
|
networkState.IsTeleportingNextFrame = true;
|
||||||
|
}
|
||||||
|
|
||||||
// Check for parenting when synchronizing and/or teleporting
|
// Check for parenting when synchronizing and/or teleporting
|
||||||
if (isSynchronization || networkState.IsTeleportingNextFrame)
|
if (isSynchronization || networkState.IsTeleportingNextFrame)
|
||||||
{
|
{
|
||||||
@@ -1691,11 +1700,13 @@ namespace Unity.Netcode.Components
|
|||||||
// values are applied.
|
// values are applied.
|
||||||
var hasParentNetworkObject = false;
|
var hasParentNetworkObject = false;
|
||||||
|
|
||||||
|
var parentNetworkObject = (NetworkObject)null;
|
||||||
|
|
||||||
// If the NetworkObject belonging to this NetworkTransform instance has a parent
|
// If the NetworkObject belonging to this NetworkTransform instance has a parent
|
||||||
// (i.e. this handles nested NetworkTransforms under a parent at some layer above)
|
// (i.e. this handles nested NetworkTransforms under a parent at some layer above)
|
||||||
if (NetworkObject.transform.parent != null)
|
if (NetworkObject.transform.parent != null)
|
||||||
{
|
{
|
||||||
var parentNetworkObject = NetworkObject.transform.parent.GetComponent<NetworkObject>();
|
parentNetworkObject = NetworkObject.transform.parent.GetComponent<NetworkObject>();
|
||||||
|
|
||||||
// In-scene placed NetworkObjects parented under a GameObject with no
|
// In-scene placed NetworkObjects parented under a GameObject with no
|
||||||
// NetworkObject preserve their lossyScale when synchronizing.
|
// NetworkObject preserve their lossyScale when synchronizing.
|
||||||
@@ -1716,28 +1727,25 @@ namespace Unity.Netcode.Components
|
|||||||
// the NetworkTransform is using world or local space synchronization.
|
// the NetworkTransform is using world or local space synchronization.
|
||||||
// WorldPositionStays: (always use world space)
|
// WorldPositionStays: (always use world space)
|
||||||
// !WorldPositionStays: (always use local space)
|
// !WorldPositionStays: (always use local space)
|
||||||
if (isSynchronization)
|
// Exception: If it is an in-scene placed NetworkObject and it is parented under a GameObject
|
||||||
|
// then always use local space unless AutoObjectParentSync is disabled and the NetworkTransform
|
||||||
|
// is synchronizing in world space.
|
||||||
|
if (isSynchronization && networkState.IsParented)
|
||||||
{
|
{
|
||||||
if (NetworkObject.WorldPositionStays())
|
var parentedUnderGameObject = NetworkObject.transform.parent != null && !parentNetworkObject && NetworkObject.IsSceneObject.Value;
|
||||||
|
if (NetworkObject.WorldPositionStays() && (!parentedUnderGameObject || (parentedUnderGameObject && !NetworkObject.AutoObjectParentSync && !InLocalSpace)))
|
||||||
{
|
{
|
||||||
position = transformToUse.position;
|
position = transformToUse.position;
|
||||||
|
networkState.InLocalSpace = false;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
position = transformToUse.localPosition;
|
position = transformToUse.localPosition;
|
||||||
|
networkState.InLocalSpace = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// All of the checks below, up to the delta position checking portion, are to determine if the
|
|
||||||
// authority changed a property during runtime that requires a full synchronizing.
|
|
||||||
if (InLocalSpace != networkState.InLocalSpace)
|
|
||||||
{
|
|
||||||
networkState.InLocalSpace = InLocalSpace;
|
|
||||||
isDirty = true;
|
|
||||||
networkState.IsTeleportingNextFrame = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Interpolate != networkState.UseInterpolation)
|
if (Interpolate != networkState.UseInterpolation)
|
||||||
{
|
{
|
||||||
networkState.UseInterpolation = Interpolate;
|
networkState.UseInterpolation = Interpolate;
|
||||||
|
|||||||
@@ -104,9 +104,11 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (peerClientIds.Length > idx)
|
||||||
peerClientIds[idx] = peerId;
|
{
|
||||||
++idx;
|
peerClientIds[idx] = peerId;
|
||||||
|
++idx;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
@@ -491,24 +493,32 @@ namespace Unity.Netcode
|
|||||||
// Process the incoming message queue so that we get everything from the server disconnecting us or, if we are the server, so we got everything from that client.
|
// Process the incoming message queue so that we get everything from the server disconnecting us or, if we are the server, so we got everything from that client.
|
||||||
MessageManager.ProcessIncomingMessageQueue();
|
MessageManager.ProcessIncomingMessageQueue();
|
||||||
|
|
||||||
InvokeOnClientDisconnectCallback(clientId);
|
|
||||||
|
|
||||||
if (LocalClient.IsHost)
|
|
||||||
{
|
|
||||||
InvokeOnPeerDisconnectedCallback(clientId);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (LocalClient.IsServer)
|
if (LocalClient.IsServer)
|
||||||
{
|
{
|
||||||
|
// We need to process the disconnection before notifying
|
||||||
OnClientDisconnectFromServer(clientId);
|
OnClientDisconnectFromServer(clientId);
|
||||||
|
|
||||||
|
// Now notify the client has disconnected
|
||||||
|
InvokeOnClientDisconnectCallback(clientId);
|
||||||
|
|
||||||
|
if (LocalClient.IsHost)
|
||||||
|
{
|
||||||
|
InvokeOnPeerDisconnectedCallback(clientId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else // As long as we are not in the middle of a shutdown
|
else
|
||||||
if (!NetworkManager.ShutdownInProgress)
|
|
||||||
{
|
{
|
||||||
// We must pass true here and not process any sends messages as we are no longer connected.
|
// Notify local client of disconnection
|
||||||
// Otherwise, attempting to process messages here can cause an exception within UnityTransport
|
InvokeOnClientDisconnectCallback(clientId);
|
||||||
// as the client ID is no longer valid.
|
|
||||||
NetworkManager.Shutdown(true);
|
// As long as we are not in the middle of a shutdown
|
||||||
|
if (!NetworkManager.ShutdownInProgress)
|
||||||
|
{
|
||||||
|
// We must pass true here and not process any sends messages as we are no longer connected.
|
||||||
|
// Otherwise, attempting to process messages here can cause an exception within UnityTransport
|
||||||
|
// as the client ID is no longer valid.
|
||||||
|
NetworkManager.Shutdown(true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (NetworkManager.IsServer)
|
if (NetworkManager.IsServer)
|
||||||
@@ -900,9 +910,14 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
ConnectedClients.Add(clientId, networkClient);
|
ConnectedClients.Add(clientId, networkClient);
|
||||||
ConnectedClientsList.Add(networkClient);
|
ConnectedClientsList.Add(networkClient);
|
||||||
var message = new ClientConnectedMessage { ClientId = clientId };
|
|
||||||
NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
|
|
||||||
ConnectedClientIds.Add(clientId);
|
ConnectedClientIds.Add(clientId);
|
||||||
|
// Host should not send this message to itself
|
||||||
|
if (clientId != NetworkManager.ServerClientId)
|
||||||
|
{
|
||||||
|
var message = new ClientConnectedMessage { ClientId = clientId };
|
||||||
|
NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
|
||||||
|
}
|
||||||
|
|
||||||
return networkClient;
|
return networkClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ namespace Unity.Netcode
|
|||||||
// RuntimeAccessModifiersILPP will make this `public`
|
// RuntimeAccessModifiersILPP will make this `public`
|
||||||
internal static readonly Dictionary<Type, Dictionary<uint, RpcReceiveHandler>> __rpc_func_table = new Dictionary<Type, Dictionary<uint, RpcReceiveHandler>>();
|
internal static readonly Dictionary<Type, Dictionary<uint, RpcReceiveHandler>> __rpc_func_table = new Dictionary<Type, Dictionary<uint, RpcReceiveHandler>>();
|
||||||
|
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
// RuntimeAccessModifiersILPP will make this `public`
|
// RuntimeAccessModifiersILPP will make this `public`
|
||||||
internal static readonly Dictionary<Type, Dictionary<uint, string>> __rpc_name_table = new Dictionary<Type, Dictionary<uint, string>>();
|
internal static readonly Dictionary<Type, Dictionary<uint, string>> __rpc_name_table = new Dictionary<Type, Dictionary<uint, string>>();
|
||||||
#endif
|
#endif
|
||||||
@@ -123,7 +123,7 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
bufferWriter.Dispose();
|
bufferWriter.Dispose();
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
|
if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
NetworkManager.NetworkMetrics.TrackRpcSent(
|
NetworkManager.NetworkMetrics.TrackRpcSent(
|
||||||
@@ -254,7 +254,7 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
bufferWriter.Dispose();
|
bufferWriter.Dispose();
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
|
if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
if (clientRpcParams.Send.TargetClientIds != null)
|
if (clientRpcParams.Send.TargetClientIds != null)
|
||||||
@@ -615,16 +615,70 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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>
|
/// <summary>
|
||||||
/// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered and the network is setup.
|
/// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered and the network is setup.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public virtual void OnNetworkSpawn() { }
|
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>
|
/// <summary>
|
||||||
/// Gets called when the <see cref="NetworkObject"/> gets despawned. Is called both on the server and clients.
|
/// Gets called when the <see cref="NetworkObject"/> gets despawned. Is called both on the server and clients.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public virtual void OnNetworkDespawn() { }
|
public virtual void OnNetworkDespawn() { }
|
||||||
|
|
||||||
|
internal void NetworkPreSpawn(ref NetworkManager networkManager)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OnNetworkPreSpawn(ref networkManager);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Debug.LogException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal void InternalOnNetworkSpawn()
|
internal void InternalOnNetworkSpawn()
|
||||||
{
|
{
|
||||||
IsSpawned = true;
|
IsSpawned = true;
|
||||||
@@ -653,6 +707,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()
|
internal void InternalOnNetworkDespawn()
|
||||||
{
|
{
|
||||||
IsSpawned = false;
|
IsSpawned = false;
|
||||||
@@ -681,7 +771,7 @@ namespace Unity.Netcode
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Invoked on all clients, override this method to be notified of any
|
/// Invoked on all clients, override this method to be notified of any
|
||||||
/// ownership changes (even if the instance was niether the previous or
|
/// ownership changes (even if the instance was niether the previous or
|
||||||
/// newly assigned current owner).
|
/// newly assigned current owner).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="previous">the previous owner</param>
|
/// <param name="previous">the previous owner</param>
|
||||||
/// <param name="current">the current owner</param>
|
/// <param name="current">the current owner</param>
|
||||||
@@ -742,7 +832,7 @@ namespace Unity.Netcode
|
|||||||
#pragma warning restore IDE1006 // restore naming rule violation check
|
#pragma warning restore IDE1006 // restore naming rule violation check
|
||||||
{
|
{
|
||||||
__rpc_func_table[GetType()][hash] = handler;
|
__rpc_func_table[GetType()][hash] = handler;
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
__rpc_name_table[GetType()][hash] = rpcMethodName;
|
__rpc_name_table[GetType()][hash] = rpcMethodName;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
@@ -768,7 +858,7 @@ namespace Unity.Netcode
|
|||||||
if (!__rpc_func_table.ContainsKey(GetType()))
|
if (!__rpc_func_table.ContainsKey(GetType()))
|
||||||
{
|
{
|
||||||
__rpc_func_table[GetType()] = new Dictionary<uint, RpcReceiveHandler>();
|
__rpc_func_table[GetType()] = new Dictionary<uint, RpcReceiveHandler>();
|
||||||
#if UNITY_EDITOR || DEVELOPMENT_BUILD
|
#if UNITY_EDITOR || DEVELOPMENT_BUILD || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
__rpc_name_table[GetType()] = new Dictionary<uint, string>();
|
__rpc_name_table[GetType()] = new Dictionary<uint, string>();
|
||||||
#endif
|
#endif
|
||||||
__initializeRpcs();
|
__initializeRpcs();
|
||||||
@@ -1223,9 +1313,9 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Invoked when the <see cref="GameObject"/> the <see cref="NetworkBehaviour"/> is attached to.
|
/// Invoked when the <see cref="GameObject"/> the <see cref="NetworkBehaviour"/> is attached to is destroyed.
|
||||||
/// NOTE: If you override this, you will want to always invoke this base class version of this
|
/// NOTE: If you override this, you should invoke this base class version of this
|
||||||
/// <see cref="OnDestroy"/> method!!
|
/// <see cref="OnDestroy"/> method.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public virtual void OnDestroy()
|
public virtual void OnDestroy()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ namespace Unity.Netcode
|
|||||||
// RuntimeAccessModifiersILPP will make this `public`
|
// RuntimeAccessModifiersILPP will make this `public`
|
||||||
internal static readonly Dictionary<uint, RpcReceiveHandler> __rpc_func_table = new Dictionary<uint, RpcReceiveHandler>();
|
internal static readonly Dictionary<uint, RpcReceiveHandler> __rpc_func_table = new Dictionary<uint, RpcReceiveHandler>();
|
||||||
|
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
// RuntimeAccessModifiersILPP will make this `public`
|
// RuntimeAccessModifiersILPP will make this `public`
|
||||||
internal static readonly Dictionary<uint, string> __rpc_name_table = new Dictionary<uint, string>();
|
internal static readonly Dictionary<uint, string> __rpc_name_table = new Dictionary<uint, string>();
|
||||||
#endif
|
#endif
|
||||||
@@ -463,20 +463,21 @@ namespace Unity.Netcode
|
|||||||
public event Action OnServerStarted = null;
|
public event Action OnServerStarted = null;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The callback to invoke once the local client is ready
|
/// The callback to invoke once the local client is ready.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public event Action OnClientStarted = null;
|
public event Action OnClientStarted = null;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// This callback is invoked once the local server is stopped.
|
/// This callback is invoked once the local server is stopped.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <remarks>The bool parameter will be set to true when stopping a host instance and false when stopping a server instance.</remarks>
|
||||||
/// <param name="arg1">The first parameter of this event will be set to <see cref="true"/> when stopping a host instance and <see cref="false"/> when stopping a server instance.</param>
|
/// <param name="arg1">The first parameter of this event will be set to <see cref="true"/> when stopping a host instance and <see cref="false"/> when stopping a server instance.</param>
|
||||||
public event Action<bool> OnServerStopped = null;
|
public event Action<bool> OnServerStopped = null;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The callback to invoke once the local client stops
|
/// The callback to invoke once the local client stops.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>The parameter states whether the client was running in host mode</remarks>
|
/// <remarks>The bool parameter will be set to true when stopping a host client and false when stopping a standard client instance.</remarks>
|
||||||
/// <param name="arg1">The first parameter of this event will be set to <see cref="true"/> when stopping the host client and <see cref="false"/> when stopping a standard client instance.</param>
|
/// <param name="arg1">The first parameter of this event will be set to <see cref="true"/> when stopping the host client and <see cref="false"/> when stopping a standard client instance.</param>
|
||||||
public event Action<bool> OnClientStopped = null;
|
public event Action<bool> OnClientStopped = null;
|
||||||
|
|
||||||
@@ -1187,7 +1188,6 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
// Everything is shutdown in the order of their dependencies
|
// Everything is shutdown in the order of their dependencies
|
||||||
DeferredMessageManager?.CleanupAllTriggers();
|
DeferredMessageManager?.CleanupAllTriggers();
|
||||||
CustomMessagingManager = null;
|
|
||||||
|
|
||||||
RpcTarget?.Dispose();
|
RpcTarget?.Dispose();
|
||||||
RpcTarget = null;
|
RpcTarget = null;
|
||||||
@@ -1198,6 +1198,8 @@ namespace Unity.Netcode
|
|||||||
// Shutdown connection manager last which shuts down transport
|
// Shutdown connection manager last which shuts down transport
|
||||||
ConnectionManager.Shutdown();
|
ConnectionManager.Shutdown();
|
||||||
|
|
||||||
|
CustomMessagingManager = null;
|
||||||
|
|
||||||
if (MessageManager != null)
|
if (MessageManager != null)
|
||||||
{
|
{
|
||||||
MessageManager.Dispose();
|
MessageManager.Dispose();
|
||||||
|
|||||||
@@ -512,6 +512,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
private void Awake()
|
private void Awake()
|
||||||
{
|
{
|
||||||
|
m_ChildNetworkBehaviours = null;
|
||||||
SetCachedParent(transform.parent);
|
SetCachedParent(transform.parent);
|
||||||
SceneOrigin = gameObject.scene;
|
SceneOrigin = gameObject.scene;
|
||||||
}
|
}
|
||||||
@@ -1360,6 +1361,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()
|
internal void InvokeBehaviourNetworkSpawn()
|
||||||
{
|
{
|
||||||
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId);
|
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId);
|
||||||
@@ -1384,6 +1397,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()
|
internal void InvokeBehaviourNetworkDespawn()
|
||||||
{
|
{
|
||||||
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId, true);
|
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId, true);
|
||||||
@@ -1886,6 +1935,9 @@ namespace Unity.Netcode
|
|||||||
// in order to be able to determine which NetworkVariables the client will be allowed to read.
|
// in order to be able to determine which NetworkVariables the client will be allowed to read.
|
||||||
networkObject.OwnerClientId = sceneObject.OwnerClientId;
|
networkObject.OwnerClientId = sceneObject.OwnerClientId;
|
||||||
|
|
||||||
|
// Special Case: Invoke NetworkBehaviour.OnPreSpawn methods here before SynchronizeNetworkBehaviours
|
||||||
|
networkObject.InvokeBehaviourNetworkPreSpawn();
|
||||||
|
|
||||||
// Synchronize NetworkBehaviours
|
// Synchronize NetworkBehaviours
|
||||||
var bufferSerializer = new BufferSerializer<BufferSerializerReader>(new BufferSerializerReader(reader));
|
var bufferSerializer = new BufferSerializer<BufferSerializerReader>(new BufferSerializerReader(reader));
|
||||||
networkObject.SynchronizeNetworkBehaviours(ref bufferSerializer, networkManager.LocalClientId);
|
networkObject.SynchronizeNetworkBehaviours(ref bufferSerializer, networkManager.LocalClientId);
|
||||||
|
|||||||
@@ -170,6 +170,12 @@ namespace Unity.Netcode
|
|||||||
networkManager.IsConnectedClient = true;
|
networkManager.IsConnectedClient = true;
|
||||||
// When scene management is disabled we notify after everything is synchronized
|
// When scene management is disabled we notify after everything is synchronized
|
||||||
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId);
|
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId);
|
||||||
|
|
||||||
|
// For convenience, notify all NetworkBehaviours that synchronization is complete.
|
||||||
|
foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList)
|
||||||
|
{
|
||||||
|
networkObject.InternalNetworkSessionSynchronized();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ConnectedClientIds.Dispose();
|
ConnectedClientIds.Dispose();
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
payload = new FastBufferReader(reader.GetUnsafePtrAtCurrentPosition(), Allocator.None, reader.Length - reader.Position);
|
payload = new FastBufferReader(reader.GetUnsafePtrAtCurrentPosition(), Allocator.None, reader.Length - reader.Position);
|
||||||
|
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
if (NetworkBehaviour.__rpc_name_table[networkBehaviour.GetType()].TryGetValue(metadata.NetworkRpcMethodId, out var rpcMethodName))
|
if (NetworkBehaviour.__rpc_name_table[networkBehaviour.GetType()].TryGetValue(metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
networkManager.NetworkMetrics.TrackRpcReceived(
|
networkManager.NetworkMetrics.TrackRpcReceived(
|
||||||
|
|||||||
@@ -36,12 +36,12 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
private protected void SendMessageToClient(NetworkBehaviour behaviour, ulong clientId, ref RpcMessage message, NetworkDelivery delivery)
|
private protected void SendMessageToClient(NetworkBehaviour behaviour, ulong clientId, ref RpcMessage message, NetworkDelivery delivery)
|
||||||
{
|
{
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
var size =
|
var size =
|
||||||
#endif
|
#endif
|
||||||
behaviour.NetworkManager.MessageManager.SendMessage(ref message, delivery, clientId);
|
behaviour.NetworkManager.MessageManager.SendMessage(ref message, delivery, clientId);
|
||||||
|
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
behaviour.NetworkManager.NetworkMetrics.TrackRpcSent(
|
behaviour.NetworkManager.NetworkMetrics.TrackRpcSent(
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ namespace Unity.Netcode
|
|||||||
message.Handle(ref context);
|
message.Handle(ref context);
|
||||||
length = tempBuffer.Length;
|
length = tempBuffer.Length;
|
||||||
}
|
}
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
behaviour.NetworkManager.NetworkMetrics.TrackRpcSent(
|
behaviour.NetworkManager.NetworkMetrics.TrackRpcSent(
|
||||||
|
|||||||
@@ -18,12 +18,12 @@ namespace Unity.Netcode
|
|||||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
||||||
{
|
{
|
||||||
var proxyMessage = new ProxyMessage { Delivery = delivery, TargetClientIds = TargetClientIds.AsArray(), WrappedMessage = message };
|
var proxyMessage = new ProxyMessage { Delivery = delivery, TargetClientIds = TargetClientIds.AsArray(), WrappedMessage = message };
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
var size =
|
var size =
|
||||||
#endif
|
#endif
|
||||||
behaviour.NetworkManager.MessageManager.SendMessage(ref proxyMessage, delivery, NetworkManager.ServerClientId);
|
behaviour.NetworkManager.MessageManager.SendMessage(ref proxyMessage, delivery, NetworkManager.ServerClientId);
|
||||||
|
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||||
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
foreach (var clientId in TargetClientIds)
|
foreach (var clientId in TargetClientIds)
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ namespace Unity.Netcode
|
|||||||
#pragma warning restore IDE0001
|
#pragma warning restore IDE0001
|
||||||
[Serializable]
|
[Serializable]
|
||||||
[GenerateSerializationForGenericParameter(0)]
|
[GenerateSerializationForGenericParameter(0)]
|
||||||
|
[GenerateSerializationForType(typeof(byte))]
|
||||||
public class AnticipatedNetworkVariable<T> : NetworkVariableBase
|
public class AnticipatedNetworkVariable<T> : NetworkVariableBase
|
||||||
{
|
{
|
||||||
[SerializeField]
|
[SerializeField]
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ namespace Unity.Netcode
|
|||||||
/// <typeparam name="T">the unmanaged type for <see cref="NetworkVariable{T}"/> </typeparam>
|
/// <typeparam name="T">the unmanaged type for <see cref="NetworkVariable{T}"/> </typeparam>
|
||||||
[Serializable]
|
[Serializable]
|
||||||
[GenerateSerializationForGenericParameter(0)]
|
[GenerateSerializationForGenericParameter(0)]
|
||||||
|
[GenerateSerializationForType(typeof(byte))]
|
||||||
public class NetworkVariable<T> : NetworkVariableBase
|
public class NetworkVariable<T> : NetworkVariableBase
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -717,7 +717,7 @@ namespace Unity.Netcode
|
|||||||
writer.WriteValueSafe(value);
|
writer.WriteValueSafe(value);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
writer.WriteByte(0);
|
writer.WriteByteSafe(0);
|
||||||
BytePacker.WriteValuePacked(writer, value.Length);
|
BytePacker.WriteValuePacked(writer, value.Length);
|
||||||
writer.WriteValueSafe(changes);
|
writer.WriteValueSafe(changes);
|
||||||
unsafe
|
unsafe
|
||||||
@@ -766,7 +766,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
if (changes.IsSet(i))
|
if (changes.IsSet(i))
|
||||||
{
|
{
|
||||||
reader.ReadByte(out ptr[i]);
|
reader.ReadByteSafe(out ptr[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -226,6 +226,11 @@ namespace Unity.Netcode
|
|||||||
foreach (var sceneToUnload in m_ScenesToUnload)
|
foreach (var sceneToUnload in m_ScenesToUnload)
|
||||||
{
|
{
|
||||||
SceneManager.UnloadSceneAsync(sceneToUnload);
|
SceneManager.UnloadSceneAsync(sceneToUnload);
|
||||||
|
// Update the ScenesLoaded when we unload scenes
|
||||||
|
if (sceneManager.ScenesLoaded.ContainsKey(sceneToUnload.handle))
|
||||||
|
{
|
||||||
|
sceneManager.ScenesLoaded.Remove(sceneToUnload.handle);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1688,6 +1688,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
|
// Add any despawned when spawned in-scene placed NetworkObjects to the scene event data
|
||||||
sceneEventData.AddDespawnedInSceneNetworkObjects();
|
sceneEventData.AddDespawnedInSceneNetworkObjects();
|
||||||
|
|
||||||
@@ -2142,6 +2153,12 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
OnSynchronizeComplete?.Invoke(NetworkManager.LocalClientId);
|
OnSynchronizeComplete?.Invoke(NetworkManager.LocalClientId);
|
||||||
|
|
||||||
|
// For convenience, notify all NetworkBehaviours that synchronization is complete.
|
||||||
|
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
|
||||||
|
{
|
||||||
|
networkObject.InternalNetworkSessionSynchronized();
|
||||||
|
}
|
||||||
|
|
||||||
EndSceneEvent(sceneEventId);
|
EndSceneEvent(sceneEventId);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -722,7 +722,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
// is not packed!
|
// is not packed!
|
||||||
InternalBuffer.ReadValueSafe(out ushort newObjectsCount);
|
InternalBuffer.ReadValueSafe(out ushort newObjectsCount);
|
||||||
|
var sceneObjects = new List<NetworkObject>();
|
||||||
for (ushort i = 0; i < newObjectsCount; i++)
|
for (ushort i = 0; i < newObjectsCount; i++)
|
||||||
{
|
{
|
||||||
var sceneObject = new NetworkObject.SceneObject();
|
var sceneObject = new NetworkObject.SceneObject();
|
||||||
@@ -734,10 +734,22 @@ namespace Unity.Netcode
|
|||||||
m_NetworkManager.SceneManager.SetTheSceneBeingSynchronized(sceneObject.NetworkSceneHandle);
|
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)
|
// Now deserialize the despawned in-scene placed NetworkObjects list (if any)
|
||||||
DeserializeDespawnedInScenePlacedNetworkObjects();
|
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
|
finally
|
||||||
{
|
{
|
||||||
@@ -983,6 +995,15 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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)
|
// Now deserialize the despawned in-scene placed NetworkObjects list (if any)
|
||||||
DeserializeDespawnedInScenePlacedNetworkObjects();
|
DeserializeDespawnedInScenePlacedNetworkObjects();
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// A helper struct for serializing <see cref="NetworkBehaviour"/>s over the network. Can be used in RPCs and <see cref="NetworkVariable{T}"/>.
|
/// A helper struct for serializing <see cref="NetworkBehaviour"/>s over the network. Can be used in RPCs and <see cref="NetworkVariable{T}"/>.
|
||||||
/// Note: network ids get recycled by the NetworkManager after a while. So a reference pointing to
|
/// Network IDs get recycled by the NetworkManager after a while, so using a NetworkBehaviourReference for too long may result in a
|
||||||
|
/// different NetworkBehaviour being returned for the assigned NetworkBehaviourId. NetworkBehaviourReferences are best for short-term
|
||||||
|
/// use when receieved via RPC or custom message, rather than for long-term references to NetworkBehaviours.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public struct NetworkBehaviourReference : INetworkSerializable, IEquatable<NetworkBehaviourReference>
|
public struct NetworkBehaviourReference : INetworkSerializable, IEquatable<NetworkBehaviourReference>
|
||||||
{
|
{
|
||||||
@@ -43,7 +45,7 @@ namespace Unity.Netcode
|
|||||||
/// <returns>True if the <see cref="NetworkBehaviour"/> was found; False if the <see cref="NetworkBehaviour"/> was not found. This can happen if the corresponding <see cref="NetworkObject"/> has not been spawned yet. you can try getting the reference at a later point in time.</returns>
|
/// <returns>True if the <see cref="NetworkBehaviour"/> was found; False if the <see cref="NetworkBehaviour"/> was not found. This can happen if the corresponding <see cref="NetworkObject"/> has not been spawned yet. you can try getting the reference at a later point in time.</returns>
|
||||||
public bool TryGet(out NetworkBehaviour networkBehaviour, NetworkManager networkManager = null)
|
public bool TryGet(out NetworkBehaviour networkBehaviour, NetworkManager networkManager = null)
|
||||||
{
|
{
|
||||||
networkBehaviour = GetInternal(this, null);
|
networkBehaviour = GetInternal(this, networkManager);
|
||||||
return networkBehaviour != null;
|
return networkBehaviour != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,7 +58,7 @@ namespace Unity.Netcode
|
|||||||
/// <returns>True if the <see cref="NetworkBehaviour"/> was found; False if the <see cref="NetworkBehaviour"/> was not found. This can happen if the corresponding <see cref="NetworkObject"/> has not been spawned yet. you can try getting the reference at a later point in time.</returns>
|
/// <returns>True if the <see cref="NetworkBehaviour"/> was found; False if the <see cref="NetworkBehaviour"/> was not found. This can happen if the corresponding <see cref="NetworkObject"/> has not been spawned yet. you can try getting the reference at a later point in time.</returns>
|
||||||
public bool TryGet<T>(out T networkBehaviour, NetworkManager networkManager = null) where T : NetworkBehaviour
|
public bool TryGet<T>(out T networkBehaviour, NetworkManager networkManager = null) where T : NetworkBehaviour
|
||||||
{
|
{
|
||||||
networkBehaviour = GetInternal(this, null) as T;
|
networkBehaviour = GetInternal(this, networkManager) as T;
|
||||||
return networkBehaviour != null;
|
return networkBehaviour != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -531,20 +531,27 @@ namespace Unity.Netcode
|
|||||||
networkObject.DestroyWithScene = sceneObject.DestroyWithScene;
|
networkObject.DestroyWithScene = sceneObject.DestroyWithScene;
|
||||||
networkObject.NetworkSceneHandle = sceneObject.NetworkSceneHandle;
|
networkObject.NetworkSceneHandle = sceneObject.NetworkSceneHandle;
|
||||||
|
|
||||||
|
|
||||||
|
var nonNetworkObjectParent = false;
|
||||||
// SPECIAL CASE FOR IN-SCENE PLACED: (only when the parent has a NetworkObject)
|
// SPECIAL CASE FOR IN-SCENE PLACED: (only when the parent has a NetworkObject)
|
||||||
// This is a special case scenario where a late joining client has joined and loaded one or
|
// This is a special case scenario where a late joining client has joined and loaded one or
|
||||||
// more scenes that contain nested in-scene placed NetworkObject children yet the server's
|
// more scenes that contain nested in-scene placed NetworkObject children yet the server's
|
||||||
// synchronization information does not indicate the NetworkObject in question has a parent.
|
// synchronization information does not indicate the NetworkObject in question has a parent.
|
||||||
// Under this scenario, we want to remove the parent before spawning and setting the transform values.
|
// Under this scenario, we want to remove the parent before spawning and setting the transform values.
|
||||||
if (sceneObject.IsSceneObject && !sceneObject.HasParent && networkObject.transform.parent != null)
|
if (sceneObject.IsSceneObject && networkObject.transform.parent != null)
|
||||||
{
|
{
|
||||||
|
var parentNetworkObject = networkObject.transform.parent.GetComponent<NetworkObject>();
|
||||||
// if the in-scene placed NetworkObject has a parent NetworkObject but the synchronization information does not
|
// if the in-scene placed NetworkObject has a parent NetworkObject but the synchronization information does not
|
||||||
// include parenting, then we need to force the removal of that parent
|
// include parenting, then we need to force the removal of that parent
|
||||||
if (networkObject.transform.parent.GetComponent<NetworkObject>() != null)
|
if (!sceneObject.HasParent && parentNetworkObject)
|
||||||
{
|
{
|
||||||
// remove the parent
|
// remove the parent
|
||||||
networkObject.ApplyNetworkParenting(true, true);
|
networkObject.ApplyNetworkParenting(true, true);
|
||||||
}
|
}
|
||||||
|
else if (sceneObject.HasParent && !parentNetworkObject)
|
||||||
|
{
|
||||||
|
nonNetworkObjectParent = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the transform unless we were spawned by a prefab handler
|
// Set the transform unless we were spawned by a prefab handler
|
||||||
@@ -554,7 +561,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
// If world position stays is true or we have auto object parent synchronization disabled
|
// If world position stays is true or we have auto object parent synchronization disabled
|
||||||
// then we want to apply the position and rotation values world space relative
|
// then we want to apply the position and rotation values world space relative
|
||||||
if (worldPositionStays || !networkObject.AutoObjectParentSync)
|
if ((worldPositionStays && !nonNetworkObjectParent) || !networkObject.AutoObjectParentSync)
|
||||||
{
|
{
|
||||||
networkObject.transform.position = position;
|
networkObject.transform.position = position;
|
||||||
networkObject.transform.rotation = rotation;
|
networkObject.transform.rotation = rotation;
|
||||||
@@ -604,7 +611,12 @@ namespace Unity.Netcode
|
|||||||
return networkObject;
|
return networkObject;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ran on both server and client
|
/// <summary>
|
||||||
|
/// Invoked when spawning locally
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Pre and Post spawn methods *CAN* be invoked prior to invoking <see cref="SpawnNetworkObjectLocallyCommon"/>
|
||||||
|
/// </remarks>
|
||||||
internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong ownerClientId, bool destroyWithScene)
|
internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong ownerClientId, bool destroyWithScene)
|
||||||
{
|
{
|
||||||
if (networkObject == null)
|
if (networkObject == null)
|
||||||
@@ -625,11 +637,21 @@ 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!");
|
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();
|
||||||
|
|
||||||
SpawnNetworkObjectLocallyCommon(networkObject, networkId, sceneObject, playerObject, ownerClientId, destroyWithScene);
|
SpawnNetworkObjectLocallyCommon(networkObject, networkId, sceneObject, playerObject, ownerClientId, destroyWithScene);
|
||||||
|
|
||||||
|
// Invoke NetworkBehaviour.OnPostSpawn methods
|
||||||
|
networkObject.InvokeBehaviourNetworkPostSpawn();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ran on both server and client
|
/// <summary>
|
||||||
|
/// Invoked from AddSceneObject
|
||||||
|
/// </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)
|
internal void SpawnNetworkObjectLocally(NetworkObject networkObject, in NetworkObject.SceneObject sceneObject, bool destroyWithScene)
|
||||||
{
|
{
|
||||||
if (networkObject == null)
|
if (networkObject == null)
|
||||||
@@ -642,7 +664,11 @@ namespace Unity.Netcode
|
|||||||
throw new SpawnStateException("Object is already spawned");
|
throw new SpawnStateException("Object 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);
|
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)
|
private void SpawnNetworkObjectLocallyCommon(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong ownerClientId, bool destroyWithScene)
|
||||||
@@ -859,7 +885,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
// If it is an in-scene placed NetworkObject then just despawn and let it be destroyed when the scene
|
// If it is an in-scene placed NetworkObject then just despawn and let it be destroyed when the scene
|
||||||
// is unloaded. Otherwise, despawn and destroy it.
|
// is unloaded. Otherwise, despawn and destroy it.
|
||||||
var shouldDestroy = !(networkObjects[i].IsSceneObject != null && networkObjects[i].IsSceneObject.Value);
|
var shouldDestroy = !(networkObjects[i].IsSceneObject == null || (networkObjects[i].IsSceneObject != null && networkObjects[i].IsSceneObject.Value));
|
||||||
|
|
||||||
// If we are going to destroy this NetworkObject, check for any in-scene placed children that need to be removed
|
// If we are going to destroy this NetworkObject, check for any in-scene placed children that need to be removed
|
||||||
if (shouldDestroy)
|
if (shouldDestroy)
|
||||||
@@ -948,11 +974,16 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
foreach (var networkObject in networkObjectsToSpawn)
|
foreach (var networkObject in networkObjectsToSpawn)
|
||||||
{
|
{
|
||||||
SpawnNetworkObjectLocally(networkObject, GetNetworkObjectId(), true, false, networkObject.OwnerClientId, true);
|
SpawnNetworkObjectLocally(networkObject, GetNetworkObjectId(), true, false, networkObject.OwnerClientId, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Notify all in-scene placed NetworkObjects have been spawned
|
||||||
|
foreach (var networkObject in networkObjectsToSpawn)
|
||||||
|
{
|
||||||
|
networkObject.InternalInSceneNetworkObjectsSpawned();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal void OnDespawnObject(NetworkObject networkObject, bool destroyGameObject)
|
internal void OnDespawnObject(NetworkObject networkObject, bool destroyGameObject)
|
||||||
|
|||||||
@@ -202,11 +202,12 @@ namespace Unity.Netcode.Transports.UTP
|
|||||||
set => m_MaxPacketQueueSize = value;
|
set => m_MaxPacketQueueSize = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
[Tooltip("The maximum size of an unreliable payload that can be handled by the transport.")]
|
[Tooltip("The maximum size of an unreliable payload that can be handled by the transport. The memory for MaxPayloadSize is allocated once per connection and is released when the connection is closed.")]
|
||||||
[SerializeField]
|
[SerializeField]
|
||||||
private int m_MaxPayloadSize = InitialMaxPayloadSize;
|
private int m_MaxPayloadSize = InitialMaxPayloadSize;
|
||||||
|
|
||||||
/// <summary>The maximum size of an unreliable payload that can be handled by the transport.</summary>
|
/// <summary>The maximum size of an unreliable payload that can be handled by the transport.</summary>
|
||||||
|
/// <remarks>The memory for MaxPayloadSize is allocated once per connection and is released when the connection is closed.</remarks>
|
||||||
public int MaxPayloadSize
|
public int MaxPayloadSize
|
||||||
{
|
{
|
||||||
get => m_MaxPayloadSize;
|
get => m_MaxPayloadSize;
|
||||||
|
|||||||
@@ -675,6 +675,11 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
|||||||
foreach (var sceneToUnload in m_ScenesToUnload)
|
foreach (var sceneToUnload in m_ScenesToUnload)
|
||||||
{
|
{
|
||||||
SceneManager.UnloadSceneAsync(sceneToUnload.Key);
|
SceneManager.UnloadSceneAsync(sceneToUnload.Key);
|
||||||
|
// Update the ScenesLoaded when we unload scenes
|
||||||
|
if (sceneManager.ScenesLoaded.ContainsKey(sceneToUnload.Key.handle))
|
||||||
|
{
|
||||||
|
sceneManager.ScenesLoaded.Remove(sceneToUnload.Key.handle);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
public IEnumerator ValidateApprovalTimeout()
|
public IEnumerator ValidateApprovalTimeout()
|
||||||
{
|
{
|
||||||
// Delay for half of the wait period
|
// Delay for half of the wait period
|
||||||
yield return new WaitForSeconds(k_TestTimeoutPeriod * 0.5f);
|
yield return new WaitForSeconds(k_TestTimeoutPeriod * 0.25f);
|
||||||
|
|
||||||
// Verify we haven't received the time out message yet
|
// Verify we haven't received the time out message yet
|
||||||
NetcodeLogAssert.LogWasNotReceived(LogType.Log, m_ExpectedLogMessage);
|
NetcodeLogAssert.LogWasNotReceived(LogType.Log, m_ExpectedLogMessage);
|
||||||
|
|||||||
@@ -182,6 +182,9 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
Assert.IsTrue(m_DisconnectedEvent[m_ServerNetworkManager].ClientId == m_ClientId, $"Expected ClientID {m_ClientId} but found ClientID {m_DisconnectedEvent[m_ServerNetworkManager].ClientId} for the server {nameof(NetworkManager)} disconnect event entry!");
|
Assert.IsTrue(m_DisconnectedEvent[m_ServerNetworkManager].ClientId == m_ClientId, $"Expected ClientID {m_ClientId} but found ClientID {m_DisconnectedEvent[m_ServerNetworkManager].ClientId} for the server {nameof(NetworkManager)} disconnect event entry!");
|
||||||
Assert.IsTrue(m_DisconnectedEvent.ContainsKey(clientManager), $"Could not find the client {nameof(NetworkManager)} disconnect event entry!");
|
Assert.IsTrue(m_DisconnectedEvent.ContainsKey(clientManager), $"Could not find the client {nameof(NetworkManager)} disconnect event entry!");
|
||||||
Assert.IsTrue(m_DisconnectedEvent[clientManager].ClientId == m_ClientId, $"Expected ClientID {m_ClientId} but found ClientID {m_DisconnectedEvent[m_ServerNetworkManager].ClientId} for the client {nameof(NetworkManager)} disconnect event entry!");
|
Assert.IsTrue(m_DisconnectedEvent[clientManager].ClientId == m_ClientId, $"Expected ClientID {m_ClientId} but found ClientID {m_DisconnectedEvent[m_ServerNetworkManager].ClientId} for the client {nameof(NetworkManager)} disconnect event entry!");
|
||||||
|
Assert.IsTrue(m_ServerNetworkManager.ConnectedClientsIds.Count == 1, $"Expected connected client identifiers count to be 1 but it was {m_ServerNetworkManager.ConnectedClientsIds.Count}!");
|
||||||
|
Assert.IsTrue(m_ServerNetworkManager.ConnectedClients.Count == 1, $"Expected connected client identifiers count to be 1 but it was {m_ServerNetworkManager.ConnectedClients.Count}!");
|
||||||
|
Assert.IsTrue(m_ServerNetworkManager.ConnectedClientsList.Count == 1, $"Expected connected client identifiers count to be 1 but it was {m_ServerNetworkManager.ConnectedClientsList.Count}!");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (m_OwnerPersistence == OwnerPersistence.DestroyWithOwner)
|
if (m_OwnerPersistence == OwnerPersistence.DestroyWithOwner)
|
||||||
|
|||||||
137
Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs
Normal file
137
Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using NUnit.Framework;
|
||||||
|
using Unity.Netcode.TestHelpers.Runtime;
|
||||||
|
using UnityEngine;
|
||||||
|
using UnityEngine.TestTools;
|
||||||
|
|
||||||
|
namespace Unity.Netcode.RuntimeTests
|
||||||
|
{
|
||||||
|
public class NetworkBehaviourPrePostSpawnTests : NetcodeIntegrationTest
|
||||||
|
{
|
||||||
|
protected override int NumberOfClients => 0;
|
||||||
|
|
||||||
|
private bool m_AllowServerToStart;
|
||||||
|
|
||||||
|
private GameObject m_PrePostSpawnObject;
|
||||||
|
|
||||||
|
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.
|
||||||
|
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 serverInstance = SpawnObject(m_PrePostSpawnObject, m_ClientNetworkManagers[0]);
|
||||||
|
var serverNetworkObject = serverInstance.GetComponent<NetworkObject>();
|
||||||
|
var serverPreSpawn = serverInstance.GetComponent<NetworkBehaviourPreSpawn>();
|
||||||
|
var serverPostSpawn = serverInstance.GetComponent<NetworkBehaviourPostSpawn>();
|
||||||
|
|
||||||
|
yield return WaitForConditionOrTimeOut(() => s_GlobalNetworkObjects.ContainsKey(m_ClientNetworkManagers[0].LocalClientId)
|
||||||
|
&& s_GlobalNetworkObjects[m_ClientNetworkManagers[0].LocalClientId].ContainsKey(serverNetworkObject.NetworkObjectId));
|
||||||
|
AssertOnTimeout($"Client-{m_ClientNetworkManagers[0].LocalClientId} failed to spawn {nameof(NetworkObject)} id-{serverNetworkObject.NetworkObjectId}!");
|
||||||
|
|
||||||
|
var clientNetworkObject = s_GlobalNetworkObjects[m_ClientNetworkManagers[0].LocalClientId][serverNetworkObject.NetworkObjectId];
|
||||||
|
var clientPreSpawn = clientNetworkObject.GetComponent<NetworkBehaviourPreSpawn>();
|
||||||
|
var clientPostSpawn = clientNetworkObject.GetComponent<NetworkBehaviourPostSpawn>();
|
||||||
|
|
||||||
|
Assert.IsTrue(serverPreSpawn.OnNetworkPreSpawnCalled, $"[Server-side] OnNetworkPreSpawn not invoked!");
|
||||||
|
Assert.IsTrue(clientPreSpawn.OnNetworkPreSpawnCalled, $"[Client-side] OnNetworkPreSpawn not invoked!");
|
||||||
|
Assert.IsTrue(serverPostSpawn.OnNetworkPostSpawnCalled, $"[Server-side] OnNetworkPostSpawn not invoked!");
|
||||||
|
Assert.IsTrue(clientPostSpawn.OnNetworkPostSpawnCalled, $"[Client-side] OnNetworkPostSpawn not invoked!");
|
||||||
|
|
||||||
|
Assert.IsTrue(serverPreSpawn.NetworkVarValueMatches, $"[Server-side][PreSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {serverPreSpawn.TestNetworkVariable.Value}!");
|
||||||
|
Assert.IsTrue(clientPreSpawn.NetworkVarValueMatches, $"[Client-side][PreSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {clientPreSpawn.TestNetworkVariable.Value}!");
|
||||||
|
|
||||||
|
Assert.IsTrue(serverPostSpawn.ValueSet == NetworkBehaviourPreSpawn.ValueToSet, $"[Server-side][PostSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {serverPostSpawn.ValueSet}!");
|
||||||
|
Assert.IsTrue(clientPostSpawn.ValueSet == NetworkBehaviourPreSpawn.ValueToSet, $"[Client-side][PostSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {clientPostSpawn.ValueSet}!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
11
Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs.meta
Normal file
11
Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 2263d66f6df15a7428d279dbdaba1519
|
||||||
|
MonoImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
serializedVersion: 2
|
||||||
|
defaultReferences: []
|
||||||
|
executionOrder: 0
|
||||||
|
icon: {instanceID: 0}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
|
using System.Collections;
|
||||||
using NUnit.Framework;
|
using NUnit.Framework;
|
||||||
|
using Unity.Collections;
|
||||||
|
using Unity.Netcode.TestHelpers.Runtime;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using UnityEngine.TestTools;
|
||||||
|
|
||||||
namespace Unity.Netcode.RuntimeTests
|
namespace Unity.Netcode.RuntimeTests
|
||||||
{
|
{
|
||||||
@@ -30,5 +34,87 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
networkManager.Shutdown();
|
networkManager.Shutdown();
|
||||||
Object.DestroyImmediate(gameObject);
|
Object.DestroyImmediate(gameObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator VerifyCustomMessageShutdownOrder()
|
||||||
|
{
|
||||||
|
Assert.True(NetcodeIntegrationTestHelpers.Create(1, out NetworkManager server, out NetworkManager[] clients));
|
||||||
|
|
||||||
|
bool isHost = false;
|
||||||
|
|
||||||
|
// Start server to cause initialization
|
||||||
|
NetcodeIntegrationTestHelpers.Start(isHost, server, clients);
|
||||||
|
|
||||||
|
// [Client-Side] Wait for a connection to the server
|
||||||
|
yield return NetcodeIntegrationTestHelpers.WaitForClientsConnected(clients, null, 512);
|
||||||
|
|
||||||
|
// [Host-Side] Check to make sure all clients are connected
|
||||||
|
yield return NetcodeIntegrationTestHelpers.WaitForClientsConnectedToServer(server, isHost ? (clients.Length + 1) : clients.Length, null, 512);
|
||||||
|
|
||||||
|
// Create a message to pass directly to the message handler. If we send the message its processed before we get a chance to shutdown
|
||||||
|
|
||||||
|
var dummySendData = new FastBufferWriter(128, Allocator.Temp);
|
||||||
|
dummySendData.WriteValueSafe("Dummy Data");
|
||||||
|
|
||||||
|
// make the message
|
||||||
|
var unnamedMessage = new UnnamedMessage
|
||||||
|
{
|
||||||
|
SendData = dummySendData
|
||||||
|
};
|
||||||
|
|
||||||
|
// make the message
|
||||||
|
using var serializedMessage = new FastBufferWriter(128, Allocator.Temp);
|
||||||
|
unnamedMessage.Serialize(serializedMessage, 0);
|
||||||
|
|
||||||
|
// Generate the full message
|
||||||
|
var messageHeader = new NetworkMessageHeader
|
||||||
|
{
|
||||||
|
MessageSize = (uint)serializedMessage.Length,
|
||||||
|
MessageType = server.MessageManager.GetMessageType(typeof(UnnamedMessage)),
|
||||||
|
};
|
||||||
|
|
||||||
|
var fullMessage = new FastBufferWriter(512, Allocator.Temp);
|
||||||
|
BytePacker.WriteValueBitPacked(fullMessage, messageHeader.MessageType);
|
||||||
|
BytePacker.WriteValueBitPacked(fullMessage, messageHeader.MessageSize);
|
||||||
|
|
||||||
|
fullMessage.WriteBytesSafe(serializedMessage.ToArray());
|
||||||
|
|
||||||
|
// Pack the message into a batch
|
||||||
|
var batchHeader = new NetworkBatchHeader
|
||||||
|
{
|
||||||
|
BatchCount = 1
|
||||||
|
};
|
||||||
|
|
||||||
|
var batchedMessage = new FastBufferWriter(1100, Allocator.Temp);
|
||||||
|
using (batchedMessage)
|
||||||
|
{
|
||||||
|
batchedMessage.TryBeginWrite(FastBufferWriter.GetWriteSize(batchHeader) +
|
||||||
|
FastBufferWriter.GetWriteSize(fullMessage));
|
||||||
|
batchedMessage.WriteValue(batchHeader);
|
||||||
|
batchedMessage.WriteBytesSafe(fullMessage.ToArray());
|
||||||
|
|
||||||
|
// Fill out the rest of the batch header
|
||||||
|
batchedMessage.Seek(0);
|
||||||
|
batchHeader = new NetworkBatchHeader
|
||||||
|
{
|
||||||
|
Magic = NetworkBatchHeader.MagicValue,
|
||||||
|
BatchSize = batchedMessage.Length,
|
||||||
|
BatchHash = XXHash.Hash64(fullMessage.ToArray()),
|
||||||
|
BatchCount = 1
|
||||||
|
};
|
||||||
|
batchedMessage.WriteValue(batchHeader);
|
||||||
|
|
||||||
|
// Handle the message as if it came from the server/client
|
||||||
|
server.MessageManager.HandleIncomingData(clients[0].LocalClientId, batchedMessage.ToArray(), 0);
|
||||||
|
|
||||||
|
foreach (var c in clients)
|
||||||
|
{
|
||||||
|
c.MessageManager.HandleIncomingData(server.LocalClientId, batchedMessage.ToArray(), 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// shutdown the network managher
|
||||||
|
NetcodeIntegrationTestHelpers.Destroy();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -751,11 +751,29 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
base.OnAuthorityPushTransformState(ref networkTransformState);
|
base.OnAuthorityPushTransformState(ref networkTransformState);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public bool AuthorityMove;
|
||||||
|
public Vector3 DirectionToMove;
|
||||||
|
public float MoveSpeed;
|
||||||
|
|
||||||
|
protected override void Update()
|
||||||
|
{
|
||||||
|
if (CanCommitToTransform && AuthorityMove)
|
||||||
|
{
|
||||||
|
transform.position += DirectionToMove * MoveSpeed * Time.deltaTime;
|
||||||
|
}
|
||||||
|
base.Update();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public delegate void NonAuthorityReceivedTransformStateDelegateHandler(ref NetworkTransformState networkTransformState);
|
||||||
|
|
||||||
|
public event NonAuthorityReceivedTransformStateDelegateHandler NonAuthorityReceivedTransformState;
|
||||||
|
|
||||||
public bool StateUpdated { get; internal set; }
|
public bool StateUpdated { get; internal set; }
|
||||||
protected override void OnNetworkTransformStateUpdated(ref NetworkTransformState oldState, ref NetworkTransformState newState)
|
protected override void OnNetworkTransformStateUpdated(ref NetworkTransformState oldState, ref NetworkTransformState newState)
|
||||||
{
|
{
|
||||||
StateUpdated = true;
|
StateUpdated = true;
|
||||||
|
NonAuthorityReceivedTransformState?.Invoke(ref newState);
|
||||||
base.OnNetworkTransformStateUpdated(ref oldState, ref newState);
|
base.OnNetworkTransformStateUpdated(ref oldState, ref newState);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -310,5 +310,64 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
Assert.True(Approximately(newScale, m_AuthoritativeTransform.transform.localScale), "Authoritative scale does not match!");
|
Assert.True(Approximately(newScale, m_AuthoritativeTransform.transform.localScale), "Authoritative scale does not match!");
|
||||||
Assert.True(Approximately(newScale, m_NonAuthoritativeTransform.transform.localScale), "Non-Authoritative scale does not match!");
|
Assert.True(Approximately(newScale, m_NonAuthoritativeTransform.transform.localScale), "Non-Authoritative scale does not match!");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Validates that the unreliable frame synchronization is correct on the
|
||||||
|
/// non-authority side when using half float precision.
|
||||||
|
/// </summary>
|
||||||
|
[Test]
|
||||||
|
public void UnreliableHalfPrecisionTest([Values] Interpolation interpolation)
|
||||||
|
{
|
||||||
|
var interpolate = interpolation != Interpolation.EnableInterpolate;
|
||||||
|
m_AuthoritativeTransform.Interpolate = interpolate;
|
||||||
|
m_NonAuthoritativeTransform.Interpolate = interpolate;
|
||||||
|
m_AuthoritativeTransform.UseHalfFloatPrecision = true;
|
||||||
|
m_NonAuthoritativeTransform.UseHalfFloatPrecision = true;
|
||||||
|
m_AuthoritativeTransform.UseUnreliableDeltas = true;
|
||||||
|
m_NonAuthoritativeTransform.UseUnreliableDeltas = true;
|
||||||
|
m_AuthoritativeTransform.AuthorityPushedTransformState += AuthorityPushedTransformState;
|
||||||
|
m_NonAuthoritativeTransform.NonAuthorityReceivedTransformState += NonAuthorityReceivedTransformState;
|
||||||
|
m_AuthoritativeTransform.MoveSpeed = 6.325f;
|
||||||
|
m_AuthoritativeTransform.AuthorityMove = true;
|
||||||
|
m_AuthoritativeTransform.DirectionToMove = GetRandomVector3(-1.0f, 1.0f);
|
||||||
|
|
||||||
|
// Iterate several times so the authority moves around enough where we get 10 frame synchs to compare against.
|
||||||
|
for (int i = 0; i < 10; i++)
|
||||||
|
{
|
||||||
|
m_AuthorityFrameSync = false;
|
||||||
|
m_NonAuthorityFrameSync = false;
|
||||||
|
VerboseDebug($"Starting with authority ({m_AuthoritativeTransform.transform.position}) and nonauthority({m_NonAuthoritativeTransform.transform.position})");
|
||||||
|
var success = WaitForConditionOrTimeOutWithTimeTravel(() => m_AuthorityFrameSync && m_NonAuthorityFrameSync, 320);
|
||||||
|
Assert.True(success, $"Timed out waiting for authority or nonauthority frame state synchronization!");
|
||||||
|
VerboseDebug($"Comparing authority ({m_AuthorityPosition}) with nonauthority({m_NonAuthorityPosition})");
|
||||||
|
Assert.True(Approximately(m_AuthorityPosition, m_NonAuthorityPosition), $"Non-Authoritative position {m_AuthorityPosition} does not match authortative position {m_NonAuthorityPosition}!");
|
||||||
|
}
|
||||||
|
|
||||||
|
m_AuthoritativeTransform.AuthorityMove = false;
|
||||||
|
m_AuthoritativeTransform.AuthorityPushedTransformState -= AuthorityPushedTransformState;
|
||||||
|
m_NonAuthoritativeTransform.NonAuthorityReceivedTransformState -= NonAuthorityReceivedTransformState;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool m_AuthorityFrameSync;
|
||||||
|
private Vector3 m_AuthorityPosition;
|
||||||
|
private bool m_NonAuthorityFrameSync;
|
||||||
|
private Vector3 m_NonAuthorityPosition;
|
||||||
|
private void AuthorityPushedTransformState(ref NetworkTransform.NetworkTransformState networkTransformState)
|
||||||
|
{
|
||||||
|
if (networkTransformState.UnreliableFrameSync)
|
||||||
|
{
|
||||||
|
m_AuthorityPosition = m_AuthoritativeTransform.GetSpaceRelativePosition();
|
||||||
|
m_AuthorityFrameSync = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void NonAuthorityReceivedTransformState(ref NetworkTransform.NetworkTransformState networkTransformState)
|
||||||
|
{
|
||||||
|
if (networkTransformState.UnreliableFrameSync)
|
||||||
|
{
|
||||||
|
m_NonAuthorityPosition = networkTransformState.NetworkDeltaPosition.GetFullPosition();
|
||||||
|
m_NonAuthorityFrameSync = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
10
package.json
10
package.json
@@ -2,23 +2,23 @@
|
|||||||
"name": "com.unity.netcode.gameobjects",
|
"name": "com.unity.netcode.gameobjects",
|
||||||
"displayName": "Netcode for GameObjects",
|
"displayName": "Netcode for GameObjects",
|
||||||
"description": "Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer.",
|
"description": "Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer.",
|
||||||
"version": "1.9.1",
|
"version": "1.10.0",
|
||||||
"unity": "2021.3",
|
"unity": "2021.3",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"com.unity.nuget.mono-cecil": "1.10.1",
|
"com.unity.nuget.mono-cecil": "1.10.1",
|
||||||
"com.unity.transport": "1.4.0"
|
"com.unity.transport": "1.4.0"
|
||||||
},
|
},
|
||||||
"_upm": {
|
"_upm": {
|
||||||
"changelog": "### Added\n- Added AnticipatedNetworkVariable<T>, which adds support for client anticipation of NetworkVariable values, allowing for more responsive gameplay (#2820)\n- Added AnticipatedNetworkTransform, which adds support for client anticipation of NetworkTransforms (#2820)\n- 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)\n- 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)\n- Added virtual method NetworkVariableBase.OnInitialize() which can be used by NetworkVariable subclasses to add initialization code (#2820)\n- 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)\n- Added NetworkTime.TickWithPartial, which represents the current tick as a double that includes the fractional/partial tick value. (#2820)\n- Added NetworkTickSystem.AnticipationTick, which can be helpful with implementation of client anticipation. This value represents the tick the current local client was at at the beginning of the most recent network round trip, which enables it to correlate server update ticks with the client tick that may have triggered them. (#2820)\n- `NetworkVariable` now includes built-in support for `NativeHashSet`, `NativeHashMap`, `List`, `HashSet`, and `Dictionary` (#2813)\n- `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)\n- `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)\n- 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)\n\n### Fixed\n\n- Fixed issue where NetworkTransformEditor would throw and exception if you excluded the physics package. (#2871)\n- Fixed issue where `NetworkTransform` could not properly synchronize its base position when using half float precision. (#2845)\n- Fixed issue where the host was not invoking `OnClientDisconnectCallback` for its own local client when internally shutting down. (#2822)\n- Fixed issue where NetworkTransform could potentially attempt to \"unregister\" a named message prior to it being registered. (#2807)\n- 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)\n\n### Changed\n\n- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2874)\n- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2872)\n- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)\n- 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)"
|
"changelog": "### Added\n\n- Added `NetworkBehaviour.OnNetworkPreSpawn` and `NetworkBehaviour.OnNetworkPostSpawn` methods that provide the ability to handle pre and post spawning actions during the `NetworkObject` spawn sequence. (#2906)\n- 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. (#2906)\n- 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. (#2906)\n\n### Fixed\n\n- Fixed issue where the realtime network stats monitor was not able to display RPC traffic in release builds due to those stats being only available in development builds or the editor. (#2980)\n- Fixed issue where `NetworkManager.ScenesLoaded` was not being updated if `PostSynchronizationSceneUnloading` was set and any loaded scenes not used during synchronization were unloaded.(#2977)\n- Fixed issue where internal delta serialization could not have a byte serializer defined when serializing deltas for other types. Added `[GenerateSerializationForType(typeof(byte))]` to both the `NetworkVariable` and `AnticipatedNetworkVariable` classes to assure a byte serializer is defined. (#2953)\n- Fixed issue with the client count not being correct on the host or server side when a client disconnects itself from a session. (#2941)\n- Fixed issue with the host trying to send itself a message that it has connected when first starting up. (#2941)\n- Fixed issue where in-scene placed NetworkObjects could be destroyed if a client disconnects early and/or before approval. (#2923)\n- Fixed issue where `NetworkDeltaPosition` would \"jitter\" periodically if both unreliable delta state updates and half-floats were used together. (#2922)\n- Fixed issue where `NetworkRigidbody2D` would not properly change body type based on the instance's authority when spawned. (#2916)\n- 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. (#2906)\n- 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. (#2895)\n\n### Changed"
|
||||||
},
|
},
|
||||||
"upmCi": {
|
"upmCi": {
|
||||||
"footprint": "0c6c6a0e036a153ff11d0b99241c93ccebfec896"
|
"footprint": "f100032a819fdef7edacd4fdfa133b189f94ef7d"
|
||||||
},
|
},
|
||||||
"documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.9/manual/index.html",
|
"documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.10/manual/index.html",
|
||||||
"repository": {
|
"repository": {
|
||||||
"url": "https://github.com/Unity-Technologies/com.unity.netcode.gameobjects.git",
|
"url": "https://github.com/Unity-Technologies/com.unity.netcode.gameobjects.git",
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"revision": "7d27c5141123e3b9f31419ccca7768a640a45d56"
|
"revision": "a342c8ddce87ae46a30dffbebb8f87ac364c0a87"
|
||||||
},
|
},
|
||||||
"samples": [
|
"samples": [
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in New Issue
Block a user