This repository has been archived on 2025-04-22. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
com.unity.netcode.gameobjects/Runtime/Configuration/NetworkConfig.cs
Unity Technologies 07f206ff9e com.unity.netcode.gameobjects@1.8.0
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

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

## [1.8.0] - 2023-12-12

### Added

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

### Fixed

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

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

345 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Collections;
using UnityEngine;
using UnityEngine.Serialization;
namespace Unity.Netcode
{
/// <summary>
/// The configuration object used to start server, client and hosts
/// </summary>
[Serializable]
public class NetworkConfig
{
/// <summary>
/// The protocol version. Different versions doesn't talk to each other.
/// </summary>
[Tooltip("Use this to make two builds incompatible with each other")]
public ushort ProtocolVersion = 0;
/// <summary>
/// The transport hosts the sever uses
/// </summary>
[Tooltip("The NetworkTransport to use")]
public NetworkTransport NetworkTransport = null;
/// <summary>
/// The default player prefab
/// </summary>
[Tooltip("When set, NetworkManager will automatically create and spawn the assigned player prefab. This can be overridden by adding it to the NetworkPrefabs list and selecting override.")]
public GameObject PlayerPrefab;
[SerializeField]
public NetworkPrefabs Prefabs = new NetworkPrefabs();
/// <summary>
/// The tickrate of network ticks. This value controls how often netcode runs user code and sends out data.
/// </summary>
[Tooltip("The tickrate. This value controls how often netcode runs user code and sends out data. The value is in 'ticks per seconds' which means a value of 50 will result in 50 ticks being executed per second or a fixed delta time of 0.02.")]
public uint TickRate = 30;
/// <summary>
/// The amount of seconds for the server to wait for the connection approval handshake to complete before the client is disconnected.
///
/// If the timeout is reached before approval is completed the client will be disconnected.
/// </summary>
/// <remarks>
/// The period begins after the <see cref="NetworkEvent.Connect"/> is received on the server.
/// The period ends once the server finishes processing a <see cref="ConnectionRequestMessage"/> from the client.
///
/// This setting is independent of any Transport-level timeouts that may be in effect. It covers the time between
/// the connection being established on the Transport layer, the client sending a
/// <see cref="ConnectionRequestMessage"/>, and the server processing that message through <see cref="ConnectionApproval"/>.
///
/// This setting is server-side only.
/// </remarks>
[Tooltip("The amount of seconds for the server to wait for the connection approval handshake to complete before the client is disconnected")]
public int ClientConnectionBufferTimeout = 10;
/// <summary>
/// Whether or not to use connection approval
/// </summary>
[Tooltip("Whether or not to force clients to be approved before they connect")]
public bool ConnectionApproval = false;
/// <summary>
/// The data to send during connection which can be used to decide on if a client should get accepted
/// </summary>
[Tooltip("The connection data sent along with connection requests")]
public byte[] ConnectionData = new byte[0];
/// <summary>
/// If your logic uses the NetworkTime, this should probably be turned off. If however it's needed to maximize accuracy, this is recommended to be turned on
/// </summary>
[Tooltip("Enable this to re-sync the NetworkTime after the initial sync")]
public bool EnableTimeResync = false;
/// <summary>
/// If time re-sync is turned on, this specifies the interval between syncs in seconds.
/// </summary>
[Tooltip("The amount of seconds between re-syncs of NetworkTime, if enabled")]
public int TimeResyncInterval = 30;
/// <summary>
/// Whether or not to ensure that NetworkVariables can be read even if a client accidentally writes where its not allowed to. This costs some CPU and bandwidth.
/// </summary>
[Tooltip("Ensures that NetworkVariables can be read even if a client accidental writes where its not allowed to. This will cost some CPU time and bandwidth")]
public bool EnsureNetworkVariableLengthSafety = false;
/// <summary>
/// Enables scene management. This will allow network scene switches and automatic scene difference corrections upon connect.
/// SoftSynced scene objects wont work with this disabled. That means that disabling SceneManagement also enables PrefabSync.
/// </summary>
[Tooltip("Enables scene management. This will allow network scene switches and automatic scene difference corrections upon connect.\n" +
"SoftSynced scene objects wont work with this disabled. That means that disabling SceneManagement also enables PrefabSync.")]
public bool EnableSceneManagement = true;
/// <summary>
/// Whether or not the netcode should check for differences in the prefabs at connection.
/// If you dynamically add prefabs at runtime, turn this OFF
/// </summary>
[Tooltip("Whether or not the netcode should check for differences in the prefab lists at connection")]
public bool ForceSamePrefabs = true;
/// <summary>
/// If true, NetworkIds will be reused after the NetworkIdRecycleDelay.
/// </summary>
[Tooltip("If true, NetworkIds will be reused after the NetworkIdRecycleDelay")]
public bool RecycleNetworkIds = true;
/// <summary>
/// The amount of seconds a NetworkId has to be unused in order for it to be reused.
/// </summary>
[Tooltip("The amount of seconds a NetworkId has to unused in order for it to be reused")]
public float NetworkIdRecycleDelay = 120f;
/// <summary>
/// Decides how many bytes to use for Rpc messaging. Leave this to 2 bytes unless you are facing hash collisions
/// </summary>
[Tooltip("The maximum amount of bytes to use for RPC messages.")]
public HashSize RpcHashSize = HashSize.VarIntFourBytes;
/// <summary>
/// The amount of seconds to wait for all clients to load or unload a requested scene
/// </summary>
[Tooltip("The amount of seconds to wait for all clients to load or unload a requested scene (only when EnableSceneManagement is enabled)")]
public int LoadSceneTimeOut = 120;
/// <summary>
/// The amount of time a message should be buffered if the asset or object needed to process it doesn't exist yet. If the asset is not added/object is not spawned within this time, it will be dropped.
/// </summary>
[Tooltip("The amount of time a message should be buffered if the asset or object needed to process it doesn't exist yet. If the asset is not added/object is not spawned within this time, it will be dropped")]
public float SpawnTimeout = 10f;
/// <summary>
/// Whether or not to enable network logs.
/// </summary>
public bool EnableNetworkLogs = true;
/// <summary>
/// The number of RTT samples that is kept as an average for calculations
/// </summary>
public const int RttAverageSamples = 5; // number of RTT to keep an average of (plus one)
/// <summary>
/// The number of slots used for RTT calculations. This is the maximum amount of in-flight messages
/// </summary>
public const int RttWindowSize = 64; // number of slots to use for RTT computations (max number of in-flight packets)
/// <summary>
/// Returns a base64 encoded version of the configuration
/// </summary>
/// <returns></returns>
public string ToBase64()
{
NetworkConfig config = this;
var writer = new FastBufferWriter(1024, Allocator.Temp);
using (writer)
{
writer.WriteValueSafe(config.ProtocolVersion);
writer.WriteValueSafe(config.TickRate);
writer.WriteValueSafe(config.ClientConnectionBufferTimeout);
writer.WriteValueSafe(config.ConnectionApproval);
writer.WriteValueSafe(config.LoadSceneTimeOut);
writer.WriteValueSafe(config.EnableTimeResync);
writer.WriteValueSafe(config.EnsureNetworkVariableLengthSafety);
writer.WriteValueSafe(config.RpcHashSize);
writer.WriteValueSafe(ForceSamePrefabs);
writer.WriteValueSafe(EnableSceneManagement);
writer.WriteValueSafe(RecycleNetworkIds);
writer.WriteValueSafe(NetworkIdRecycleDelay);
writer.WriteValueSafe(EnableNetworkLogs);
// Allocates
return Convert.ToBase64String(writer.ToArray());
}
}
/// <summary>
/// Sets the NetworkConfig data with that from a base64 encoded version
/// </summary>
/// <param name="base64">The base64 encoded version</param>
public void FromBase64(string base64)
{
NetworkConfig config = this;
byte[] binary = Convert.FromBase64String(base64);
using var reader = new FastBufferReader(binary, Allocator.Temp);
using (reader)
{
reader.ReadValueSafe(out config.ProtocolVersion);
reader.ReadValueSafe(out config.TickRate);
reader.ReadValueSafe(out config.ClientConnectionBufferTimeout);
reader.ReadValueSafe(out config.ConnectionApproval);
reader.ReadValueSafe(out config.LoadSceneTimeOut);
reader.ReadValueSafe(out config.EnableTimeResync);
reader.ReadValueSafe(out config.EnsureNetworkVariableLengthSafety);
reader.ReadValueSafe(out config.RpcHashSize);
reader.ReadValueSafe(out config.ForceSamePrefabs);
reader.ReadValueSafe(out config.EnableSceneManagement);
reader.ReadValueSafe(out config.RecycleNetworkIds);
reader.ReadValueSafe(out config.NetworkIdRecycleDelay);
reader.ReadValueSafe(out config.EnableNetworkLogs);
}
}
private ulong? m_ConfigHash = null;
/// <summary>
/// Clears out the configuration hash value generated for a specific network session
/// </summary>
internal void ClearConfigHash()
{
m_ConfigHash = null;
}
/// <summary>
/// Gets a SHA256 hash of parts of the NetworkConfig instance
/// </summary>
/// <param name="cache"></param>
/// <returns></returns>
public ulong GetConfig(bool cache = true)
{
if (m_ConfigHash != null && cache)
{
return m_ConfigHash.Value;
}
var writer = new FastBufferWriter(1024, Allocator.Temp, int.MaxValue);
using (writer)
{
writer.WriteValueSafe(ProtocolVersion);
writer.WriteValueSafe(NetworkConstants.PROTOCOL_VERSION);
if (ForceSamePrefabs)
{
var sortedDictionary = Prefabs.NetworkPrefabOverrideLinks.OrderBy(x => x.Key);
foreach (var sortedEntry in sortedDictionary)
{
writer.WriteValueSafe(sortedEntry.Key);
}
}
writer.WriteValueSafe(TickRate);
writer.WriteValueSafe(ConnectionApproval);
writer.WriteValueSafe(ForceSamePrefabs);
writer.WriteValueSafe(EnableSceneManagement);
writer.WriteValueSafe(EnsureNetworkVariableLengthSafety);
writer.WriteValueSafe(RpcHashSize);
if (cache)
{
m_ConfigHash = XXHash.Hash64(writer.ToArray());
return m_ConfigHash.Value;
}
return XXHash.Hash64(writer.ToArray());
}
}
/// <summary>
/// Compares a SHA256 hash with the current NetworkConfig instances hash
/// </summary>
/// <param name="hash"></param>
/// <returns></returns>
public bool CompareConfig(ulong hash)
{
return hash == GetConfig();
}
internal void InitializePrefabs()
{
if (HasOldPrefabList())
{
MigrateOldNetworkPrefabsToNetworkPrefabsList();
}
Prefabs.Initialize();
}
[NonSerialized]
private bool m_DidWarnOldPrefabList = false;
private void WarnOldPrefabList()
{
if (!m_DidWarnOldPrefabList)
{
Debug.LogWarning("Using Legacy Network Prefab List. Consider Migrating.");
m_DidWarnOldPrefabList = true;
}
}
/// <summary>
/// Returns true if the old List&lt;NetworkPrefab&gt; serialized data is present.
/// </summary>
/// <remarks>
/// Internal use only to help migrate projects. <seealso cref="MigrateOldNetworkPrefabsToNetworkPrefabsList"/></remarks>
internal bool HasOldPrefabList()
{
return OldPrefabList?.Count > 0;
}
/// <summary>
/// Migrate the old format List&lt;NetworkPrefab&gt; prefab registration to the new NetworkPrefabsList ScriptableObject.
/// </summary>
/// <remarks>
/// OnAfterDeserialize cannot instantiate new objects (e.g. NetworkPrefabsList SO) since it executes in a thread, so we have to do it later.
/// Since NetworkConfig isn't a Unity.Object it doesn't get an Awake callback, so we have to do this in NetworkManager and expose this API.
/// </remarks>
internal NetworkPrefabsList MigrateOldNetworkPrefabsToNetworkPrefabsList()
{
if (OldPrefabList == null || OldPrefabList.Count == 0)
{
return null;
}
if (Prefabs == null)
{
throw new Exception("Prefabs field is null.");
}
Prefabs.NetworkPrefabsLists.Add(ScriptableObject.CreateInstance<NetworkPrefabsList>());
if (OldPrefabList?.Count > 0)
{
// Migrate legacy types/fields
foreach (var networkPrefab in OldPrefabList)
{
Prefabs.NetworkPrefabsLists[Prefabs.NetworkPrefabsLists.Count - 1].Add(networkPrefab);
}
}
OldPrefabList = null;
return Prefabs.NetworkPrefabsLists[Prefabs.NetworkPrefabsLists.Count - 1];
}
[FormerlySerializedAs("NetworkPrefabs")]
[SerializeField]
internal List<NetworkPrefab> OldPrefabList;
}
}