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/NetworkPrefabs.cs
Unity Technologies 4d70c198bd com.unity.netcode.gameobjects@1.5.1
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.5.1] - 2023-06-07

### Added

- Added support for serializing `NativeArray<>` and `NativeList<>` in `FastBufferReader`/`FastBufferWriter`, `BufferSerializer`, `NetworkVariable`, and RPCs. (To use `NativeList<>`, add `UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT` to your Scripting Define Symbols in `Project Settings > Player`) (#2375)
- The location of the automatically-created default network prefab list can now be configured (#2544)
- Added: Message size limits (max single message and max fragmented message) can now be set using NetworkManager.MaximumTransmissionUnitSize and NetworkManager.MaximumFragmentedMessageSize for transports that don't work with the default values (#2530)
- Added `NetworkObject.SpawnWithObservers` property (default is true) that when set to false will spawn a `NetworkObject` with no observers and will not be spawned on any client until `NetworkObject.NetworkShow` is invoked. (#2568)

### Fixed

- Fixed: Fixed a null reference in codegen in some projects (#2581)
- Fixed issue where the `OnClientDisconnected` client identifier was incorrect after a pending client connection was denied. (#2569)
- Fixed warning "Runtime Network Prefabs was not empty at initialization time." being erroneously logged when no runtime network prefabs had been added (#2565)
- Fixed issue where some temporary debug console logging was left in a merged PR. (#2562)
- Fixed the "Generate Default Network Prefabs List" setting not loading correctly and always reverting to being checked. (#2545)
- Fixed issue where users could not use NetworkSceneManager.VerifySceneBeforeLoading to exclude runtime generated scenes from client synchronization. (#2550)
- Fixed missing value on `NetworkListEvent` for `EventType.RemoveAt` events.  (#2542,#2543)
- Fixed issue where parenting a NetworkTransform under a transform with a scale other than Vector3.one would result in incorrect values on non-authoritative instances. (#2538)
- Fixed issue where a server would include scene migrated and then despawned NetworkObjects to a client that was being synchronized. (#2532)
- Fixed the inspector throwing exceptions when attempting to render `NetworkVariable`s of enum types. (#2529)
- Making a `NetworkVariable` with an `INetworkSerializable` type that doesn't meet the `new()` constraint will now create a compile-time error instead of an editor crash (#2528)
- Fixed Multiplayer Tools package installation docs page link on the NetworkManager popup. (#2526)
- Fixed an exception and error logging when two different objects are shown and hidden on the same frame (#2524)
- Fixed a memory leak in `UnityTransport` that occurred if `StartClient` failed. (#2518)
- Fixed issue where a client could throw an exception if abruptly disconnected from a network session with one or more spawned `NetworkObject`(s). (#2510)
- Fixed issue where invalid endpoint addresses were not being detected and returning false from NGO UnityTransport. (#2496)
- Fixed some errors that could occur if a connection is lost and the loss is detected when attempting to write to the socket. (#2495)

## Changed

- Adding network prefabs before NetworkManager initialization is now supported. (#2565)
- Connecting clients being synchronized now switch to the server's active scene before spawning and synchronizing NetworkObjects. (#2532)
- Updated `UnityTransport` dependency on `com.unity.transport` to 1.3.4. (#2533)
- Improved performance of NetworkBehaviour initialization by replacing reflection when initializing NetworkVariables with compile-time code generation, which should help reduce hitching during additive scene loads. (#2522)
2023-06-07 00:00:00 +00:00

329 lines
12 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// A class that represents the runtime aspect of network prefabs.
/// This class contains processed prefabs from the NetworkPrefabsList, as
/// well as additional modifications (additions and removals) made at runtime.
/// </summary>
[Serializable]
public class NetworkPrefabs
{
/// <summary>
/// Edit-time scripted object containing a list of NetworkPrefabs.
/// </summary>
/// <remarks>
/// This field can be null if no prefabs are pre-configured.
/// Runtime usages of <see cref="NetworkPrefabs"/> should not depend on this edit-time field for execution.
/// </remarks>
[SerializeField]
public List<NetworkPrefabsList> NetworkPrefabsLists = new List<NetworkPrefabsList>();
/// <summary>
/// This dictionary provides a quick way to check and see if a NetworkPrefab has a NetworkPrefab override.
/// Generated at runtime and OnValidate
/// </summary>
[NonSerialized]
public Dictionary<uint, NetworkPrefab> NetworkPrefabOverrideLinks = new Dictionary<uint, NetworkPrefab>();
[NonSerialized]
public Dictionary<uint, uint> OverrideToNetworkPrefab = new Dictionary<uint, uint>();
public IReadOnlyList<NetworkPrefab> Prefabs => m_Prefabs;
[NonSerialized]
private List<NetworkPrefab> m_Prefabs = new List<NetworkPrefab>();
[NonSerialized]
private List<NetworkPrefab> m_RuntimeAddedPrefabs = new List<NetworkPrefab>();
private void AddTriggeredByNetworkPrefabList(NetworkPrefab networkPrefab)
{
if (AddPrefabRegistration(networkPrefab))
{
// Don't add this to m_RuntimeAddedPrefabs
// This prefab is now in the PrefabList, so if we shutdown and initialize again, we'll pick it up from there.
m_Prefabs.Add(networkPrefab);
}
}
private void RemoveTriggeredByNetworkPrefabList(NetworkPrefab networkPrefab)
{
m_Prefabs.Remove(networkPrefab);
}
~NetworkPrefabs()
{
Shutdown();
}
/// <summary>
/// Deregister from add and remove events
/// Clear the list
/// </summary>
internal void Shutdown()
{
foreach (var list in NetworkPrefabsLists)
{
list.OnAdd -= AddTriggeredByNetworkPrefabList;
list.OnRemove -= RemoveTriggeredByNetworkPrefabList;
}
}
/// <summary>
/// Processes the <see cref="NetworkPrefabsList"/> if one is present for use during runtime execution,
/// else processes <see cref="Prefabs"/>.
/// </summary>
public void Initialize(bool warnInvalid = true)
{
m_Prefabs.Clear();
foreach (var list in NetworkPrefabsLists)
{
list.OnAdd += AddTriggeredByNetworkPrefabList;
list.OnRemove += RemoveTriggeredByNetworkPrefabList;
}
NetworkPrefabOverrideLinks.Clear();
OverrideToNetworkPrefab.Clear();
var prefabs = new List<NetworkPrefab>();
if (NetworkPrefabsLists.Count != 0)
{
foreach (var list in NetworkPrefabsLists)
{
foreach (var networkPrefab in list.PrefabList)
{
prefabs.Add(networkPrefab);
}
}
}
m_Prefabs = new List<NetworkPrefab>();
List<NetworkPrefab> removeList = null;
if (warnInvalid)
{
removeList = new List<NetworkPrefab>();
}
foreach (var networkPrefab in prefabs)
{
if (AddPrefabRegistration(networkPrefab))
{
m_Prefabs.Add(networkPrefab);
}
else
{
removeList?.Add(networkPrefab);
}
}
foreach (var networkPrefab in m_RuntimeAddedPrefabs)
{
if (AddPrefabRegistration(networkPrefab))
{
m_Prefabs.Add(networkPrefab);
}
else
{
removeList?.Add(networkPrefab);
}
}
// Clear out anything that is invalid or not used
if (removeList?.Count > 0)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
var sb = new StringBuilder("Removing invalid prefabs from Network Prefab registration: ");
sb.Append(string.Join(", ", removeList));
NetworkLog.LogWarning(sb.ToString());
}
}
}
/// <summary>
/// Add a new NetworkPrefab instance to the list
/// </summary>
/// <remarks>
/// The framework does not synchronize this list between clients. Any runtime changes must be handled manually.
///
/// Any modifications made here are not persisted. Permanent configuration changes should be done
/// through the <see cref="NetworkPrefabsList"/> scriptable object property.
/// </remarks>
public bool Add(NetworkPrefab networkPrefab)
{
if (AddPrefabRegistration(networkPrefab))
{
m_Prefabs.Add(networkPrefab);
m_RuntimeAddedPrefabs.Add(networkPrefab);
return true;
}
return false;
}
/// <summary>
/// Remove a NetworkPrefab instance from the list
/// </summary>
/// <remarks>
/// The framework does not synchronize this list between clients. Any runtime changes must be handled manually.
///
/// Any modifications made here are not persisted. Permanent configuration changes should be done
/// through the <see cref="NetworkPrefabsList"/> scriptable object property.
/// </remarks>
public void Remove(NetworkPrefab prefab)
{
if (prefab == null)
{
throw new ArgumentNullException(nameof(prefab));
}
m_Prefabs.Remove(prefab);
m_RuntimeAddedPrefabs.Remove(prefab);
OverrideToNetworkPrefab.Remove(prefab.TargetPrefabGlobalObjectIdHash);
NetworkPrefabOverrideLinks.Remove(prefab.SourcePrefabGlobalObjectIdHash);
}
/// <summary>
/// Remove a NetworkPrefab instance with matching <see cref="NetworkPrefab.Prefab"/> from the list
/// </summary>
/// <remarks>
/// The framework does not synchronize this list between clients. Any runtime changes must be handled manually.
///
/// Any modifications made here are not persisted. Permanent configuration changes should be done
/// through the <see cref="NetworkPrefabsList"/> scriptable object property.
/// </remarks>
public void Remove(GameObject prefab)
{
if (prefab == null)
{
throw new ArgumentNullException(nameof(prefab));
}
for (int i = 0; i < m_Prefabs.Count; i++)
{
if (m_Prefabs[i].Prefab == prefab)
{
Remove(m_Prefabs[i]);
return;
}
}
for (int i = 0; i < m_RuntimeAddedPrefabs.Count; i++)
{
if (m_RuntimeAddedPrefabs[i].Prefab == prefab)
{
Remove(m_RuntimeAddedPrefabs[i]);
return;
}
}
}
/// <summary>
/// Check if the given GameObject is present as a prefab within the list
/// </summary>
/// <param name="prefab">The prefab to check</param>
/// <returns>Whether or not the prefab exists</returns>
public bool Contains(GameObject prefab)
{
for (int i = 0; i < m_Prefabs.Count; i++)
{
if (m_Prefabs[i].Prefab == prefab)
{
return true;
}
}
return false;
}
/// <summary>
/// Check if the given NetworkPrefab is present within the list
/// </summary>
/// <param name="prefab">The prefab to check</param>
/// <returns>Whether or not the prefab exists</returns>
public bool Contains(NetworkPrefab prefab)
{
for (int i = 0; i < m_Prefabs.Count; i++)
{
if (m_Prefabs[i].Equals(prefab))
{
return true;
}
}
return false;
}
/// <summary>
/// Configures <see cref="NetworkPrefabOverrideLinks"/> and <see cref="OverrideToNetworkPrefab"/> for the given <see cref="NetworkPrefab"/>
/// </summary>
private bool AddPrefabRegistration(NetworkPrefab networkPrefab)
{
if (networkPrefab == null)
{
return false;
}
// Safeguard validation check since this method is called from outside of NetworkConfig and we can't control what's passed in.
if (!networkPrefab.Validate())
{
return false;
}
uint source = networkPrefab.SourcePrefabGlobalObjectIdHash;
uint target = networkPrefab.TargetPrefabGlobalObjectIdHash;
// Make sure the prefab isn't already registered.
if (NetworkPrefabOverrideLinks.ContainsKey(source))
{
var networkObject = networkPrefab.Prefab.GetComponent<NetworkObject>();
// This should never happen, but in the case it somehow does log an error and remove the duplicate entry
Debug.LogError($"{nameof(NetworkPrefab)} ({networkObject.name}) has a duplicate {nameof(NetworkObject.GlobalObjectIdHash)} source entry value of: {source}!");
return false;
}
// If we don't have an override configured, registration is simple!
if (networkPrefab.Override == NetworkPrefabOverride.None)
{
NetworkPrefabOverrideLinks.Add(source, networkPrefab);
return true;
}
// Make sure we don't have several overrides targeting the same prefab. Apparently we don't support that... shame.
if (OverrideToNetworkPrefab.ContainsKey(target))
{
var networkObject = networkPrefab.Prefab.GetComponent<NetworkObject>();
// This can happen if a user tries to make several GlobalObjectIdHash values point to the same target
Debug.LogError($"{nameof(NetworkPrefab)} (\"{networkObject.name}\") has a duplicate {nameof(NetworkObject.GlobalObjectIdHash)} target entry value of: {target}!");
return false;
}
switch (networkPrefab.Override)
{
case NetworkPrefabOverride.Prefab:
{
NetworkPrefabOverrideLinks.Add(source, networkPrefab);
OverrideToNetworkPrefab.Add(target, source);
}
break;
case NetworkPrefabOverride.Hash:
{
NetworkPrefabOverrideLinks.Add(source, networkPrefab);
OverrideToNetworkPrefab.Add(target, source);
}
break;
}
return true;
}
}
}