From 4e3e196b482d4958b634ba5f92e9590e91c045ed Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Wed, 25 Aug 2021 16:57:48 -0700 Subject: [PATCH 1/8] refactor!: remove network variable settings, network behaviour cleanup --- .../Runtime/Core/NetworkBehaviour.cs | 52 ++++++------ .../Runtime/Core/NetworkObject.cs | 10 ++- .../Messaging/InternalMessageHandler.cs | 2 +- .../NetworkVariable/ClientNetworkVariable.cs | 8 +- .../Collections/NetworkDictionary.cs | 22 ++--- .../Collections/NetworkList.cs | 28 ++----- .../NetworkVariable/Collections/NetworkSet.cs | 18 +---- .../NetworkVariable/NetworkVariable.cs | 27 +++---- .../NetworkVariable/NetworkVariableBase.cs | 38 +++++---- .../NetworkVariableSettings.cs | 19 ----- .../NetworkVariableSettings.cs.meta | 11 --- .../Runtime/Spawning/NetworkSpawnManager.cs | 14 ++-- .../NetworkVariableTestComponent.cs | 80 +++++++++---------- .../Tests/Runtime/NetworkVariableTests.cs | 2 +- 14 files changed, 126 insertions(+), 205 deletions(-) delete mode 100644 com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs delete mode 100644 com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs.meta diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index d871509288..bb379d50f2 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -425,7 +425,7 @@ internal void InitializeVariables() sortedFields[i].SetValue(this, instance); } - instance.NetworkBehaviour = this; + instance.Initialize(this); var instanceNameProperty = fieldType.GetProperty(nameof(NetworkVariableBase.Name)); var sanitizedVariableName = sortedFields[i].Name.Replace("<", string.Empty).Replace(">k__BackingField", string.Empty); @@ -624,15 +624,15 @@ private bool CouldHaveDirtyNetworkVariables() return false; } - internal static void HandleNetworkVariableDeltas(List networkVariableList, Stream stream, ulong clientId, NetworkBehaviour logInstance, NetworkManager networkManager) + internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, NetworkBehaviour logInstance) { using (var reader = PooledNetworkReader.Get(stream)) { - for (int i = 0; i < networkVariableList.Count; i++) + for (int i = 0; i < NetworkVariableFields.Count; i++) { ushort varSize = 0; - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { varSize = reader.ReadUInt16Packed(); @@ -649,15 +649,15 @@ internal static void HandleNetworkVariableDeltas(List netwo } } - if (networkManager.IsServer && !networkVariableList[i].CanClientWrite(clientId)) + if (NetworkManager.IsServer && !NetworkVariableFields[i].CanClientWrite(clientId)) { // we are choosing not to fire an exception here, because otherwise a malicious client could use this to crash the server - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { NetworkLog.LogWarning($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); - NetworkLog.LogError($"[{networkVariableList[i].GetType().Name}]"); + NetworkLog.LogError($"[{NetworkVariableFields[i].GetType().Name}]"); } stream.Position += varSize; @@ -674,25 +674,25 @@ internal static void HandleNetworkVariableDeltas(List netwo if (NetworkLog.CurrentLogLevel <= LogLevel.Error) { NetworkLog.LogError($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. No more variables can be read. This is critical. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); - NetworkLog.LogError($"[{networkVariableList[i].GetType().Name}]"); + NetworkLog.LogError($"[{NetworkVariableFields[i].GetType().Name}]"); } return; } long readStartPos = stream.Position; - networkVariableList[i].ReadDelta(stream, networkManager.IsServer); - networkManager.NetworkMetrics.TrackNetworkVariableDeltaReceived( + NetworkVariableFields[i].ReadDelta(stream, NetworkManager.IsServer); + NetworkManager.NetworkMetrics.TrackNetworkVariableDeltaReceived( clientId, logInstance.NetworkObjectId, logInstance.name, - networkVariableList[i].Name, + NetworkVariableFields[i].Name, logInstance.__getTypeName(), stream.Length); (stream as NetworkBuffer).SkipPadBits(); - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (stream.Position > (readStartPos + varSize)) { @@ -717,20 +717,20 @@ internal static void HandleNetworkVariableDeltas(List netwo } } - internal static void WriteNetworkVariableData(List networkVariableList, Stream stream, ulong clientId, NetworkManager networkManager) + internal void WriteNetworkVariableData(Stream stream, ulong clientId) { - if (networkVariableList.Count == 0) + if (NetworkVariableFields.Count == 0) { return; } using (var writer = PooledNetworkWriter.Get(stream)) { - for (int j = 0; j < networkVariableList.Count; j++) + for (int j = 0; j < NetworkVariableFields.Count; j++) { - bool canClientRead = networkVariableList[j].CanClientRead(clientId); + bool canClientRead = NetworkVariableFields[j].CanClientRead(clientId); - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (!canClientRead) { @@ -744,11 +744,11 @@ internal static void WriteNetworkVariableData(List networkV if (canClientRead) { - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { using (var varBuffer = PooledNetworkBuffer.Get()) { - networkVariableList[j].WriteField(varBuffer); + NetworkVariableFields[j].WriteField(varBuffer); varBuffer.PadBuffer(); writer.WriteUInt16Packed((ushort)varBuffer.Length); @@ -757,7 +757,7 @@ internal static void WriteNetworkVariableData(List networkV } else { - networkVariableList[j].WriteField(stream); + NetworkVariableFields[j].WriteField(stream); writer.WritePadBits(); } } @@ -765,20 +765,20 @@ internal static void WriteNetworkVariableData(List networkV } } - internal static void SetNetworkVariableData(List networkVariableList, Stream stream, NetworkManager networkManager) + internal void SetNetworkVariableData(Stream stream) { - if (networkVariableList.Count == 0) + if (NetworkVariableFields.Count == 0) { return; } using (var reader = PooledNetworkReader.Get(stream)) { - for (int j = 0; j < networkVariableList.Count; j++) + for (int j = 0; j < NetworkVariableFields.Count; j++) { ushort varSize = 0; - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { varSize = reader.ReadUInt16Packed(); @@ -797,10 +797,10 @@ internal static void SetNetworkVariableData(List networkVar long readStartPos = stream.Position; - networkVariableList[j].ReadField(stream); + NetworkVariableFields[j].ReadField(stream); reader.SkipPadBits(); - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (stream is NetworkBuffer networkBuffer) { diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs index 9b60dc3862..53d16f0b9a 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs @@ -872,8 +872,9 @@ internal void WriteNetworkVariableData(Stream stream, ulong clientId) { for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { - ChildNetworkBehaviours[i].InitializeVariables(); - NetworkBehaviour.WriteNetworkVariableData(ChildNetworkBehaviours[i].NetworkVariableFields, stream, clientId, NetworkManager); + var behavior = ChildNetworkBehaviours[i]; + behavior.InitializeVariables(); + behavior.WriteNetworkVariableData(stream, clientId); } } @@ -881,8 +882,9 @@ internal void SetNetworkVariableData(Stream stream) { for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { - ChildNetworkBehaviours[i].InitializeVariables(); - NetworkBehaviour.SetNetworkVariableData(ChildNetworkBehaviours[i].NetworkVariableFields, stream, NetworkManager); + var behaviour = ChildNetworkBehaviours[i]; + behaviour.InitializeVariables(); + behaviour.SetNetworkVariableData(stream); } } diff --git a/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs b/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs index 6bce802f67..fd4249c65c 100644 --- a/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs +++ b/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs @@ -222,7 +222,7 @@ public void HandleNetworkVariableDelta(ulong clientId, Stream stream) } else { - NetworkBehaviour.HandleNetworkVariableDeltas(instance.NetworkVariableFields, stream, clientId, instance, NetworkManager); + instance.HandleNetworkVariableDeltas(stream, clientId, instance); } } else if (NetworkManager.IsServer) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs index 6d5c5e03f1..e187741189 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs @@ -15,16 +15,16 @@ public class ClientNetworkVariable : NetworkVariable where T : unmanaged { public ClientNetworkVariable() { } - public ClientNetworkVariable(NetworkVariableSettings settings) : base(settings) { } + public ClientNetworkVariable(NetworkVariableReadPermission readPerm) : base(readPerm) { } public override bool CanClientWrite(ulong clientId) { - return NetworkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; } public override bool ShouldWrite(ulong clientId, bool isServer) { - return m_IsDirty && !isServer && NetworkBehaviour.IsOwner; + return m_IsDirty && !isServer && m_NetworkBehaviour.IsOwner; } /// @@ -40,7 +40,7 @@ public override T Value // Also, note this is not really very water-tight, if you are running as a host // we cannot tell if a ClientNetworkVariable write is happening inside server-ish code - if (NetworkBehaviour.NetworkManager.IsServer) + if (m_NetworkBehaviour.NetworkManager.IsServer) { throw new InvalidOperationException("Server not allowed to write to ClientNetworkVariables"); } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 5e533124f5..6adde145b5 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -34,15 +34,15 @@ public NetworkDictionary() { } /// /// Creates a NetworkDictionary with the default value and custom settings /// - /// The settings to use for the NetworkDictionary - public NetworkDictionary(NetworkVariableSettings settings) : base(settings) { } + /// The read permission to use for this NetworkDictionary + public NetworkDictionary(NetworkVariableReadPermission readPerm) : base(readPerm) { } /// /// Creates a NetworkDictionary with a custom value and custom settings /// - /// The settings to use for the NetworkDictionary + /// The read permission to use for this NetworkDictionary /// The initial value to use for the NetworkDictionary - public NetworkDictionary(NetworkVariableSettings settings, IDictionary value) : base(settings) + public NetworkDictionary(NetworkVariableReadPermission readPerm, IDictionary value) : base(readPerm) { m_Dictionary = value; } @@ -448,11 +448,7 @@ IEnumerator IEnumerable.GetEnumerator() private void HandleAddDictionaryEvent(NetworkDictionaryEvent dictionaryEvent) { - if (NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) - { - m_DirtyEvents.Add(dictionaryEvent); - } - + m_DirtyEvents.Add(dictionaryEvent); OnDictionaryChanged?.Invoke(dictionaryEvent); } @@ -464,14 +460,6 @@ public int LastModifiedTick return NetworkTickSystem.NoTick; } } - - private void EnsureInitialized() - { - if (NetworkBehaviour == null) - { - throw new InvalidOperationException("Cannot access " + nameof(NetworkDictionary) + " before it's initialized"); - } - } } /// diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index e19dc4eaa0..74acdabf05 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -14,11 +14,6 @@ public class NetworkList : NetworkVariableBase, IList where T : unmanaged private readonly IList m_List = new List(); private readonly List> m_DirtyEvents = new List>(); - /// - /// Gets the last time the variable was synced - /// - public NetworkTime LastSyncedTime { get; internal set; } - /// /// Delegate type for list changed event /// @@ -38,15 +33,15 @@ public NetworkList() { } /// /// Creates a NetworkList with the default value and custom settings /// - /// The settings to use for the NetworkList - public NetworkList(NetworkVariableSettings settings) : base(settings) { } + /// The read permission to use for the NetworkList + public NetworkList(NetworkVariableReadPermission readPerm) : base(readPerm) { } /// /// Creates a NetworkList with a custom value and custom settings /// - /// The settings to use for the NetworkList + /// The read permission to use for the NetworkList /// The initial value to use for the NetworkList - public NetworkList(NetworkVariableSettings settings, IList value) : base(settings) + public NetworkList(NetworkVariableReadPermission readPerm, IList value) : base(readPerm) { m_List = value; } @@ -65,7 +60,6 @@ public override void ResetDirty() { base.ResetDirty(); m_DirtyEvents.Clear(); - LastSyncedTime = NetworkBehaviour.NetworkManager.LocalTime; } /// @@ -459,11 +453,7 @@ public T this[int index] private void HandleAddListEvent(NetworkListEvent listEvent) { - if (NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) - { - m_DirtyEvents.Add(listEvent); - } - + m_DirtyEvents.Add(listEvent); OnListChanged?.Invoke(listEvent); } @@ -475,14 +465,6 @@ public int LastModifiedTick return NetworkTickSystem.NoTick; } } - - private void EnsureInitialized() - { - if (NetworkBehaviour == null) - { - throw new InvalidOperationException("Cannot access " + nameof(NetworkList) + " before it's initialized"); - } - } } /// diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index 865e8f45fc..b689a19238 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -15,11 +15,6 @@ public class NetworkSet : NetworkVariableBase, ISet where T: unmanaged private readonly ISet m_Set = new HashSet(); private readonly List> m_DirtyEvents = new List>(); - /// - /// Gets the last time the variable was synced - /// - public NetworkTime LastSyncedTime { get; internal set; } - /// /// Delegate type for set changed event /// @@ -40,14 +35,14 @@ public NetworkSet() { } /// Creates a NetworkSet with the default value and custom settings /// /// The settings to use for the NetworkList - public NetworkSet(NetworkVariableSettings settings) : base(settings) { } + public NetworkSet(NetworkVariableReadPermission readPerm) : base(readPerm) { } /// /// Creates a NetworkSet with a custom value and custom settings /// /// The settings to use for the NetworkSet /// The initial value to use for the NetworkSet - public NetworkSet(NetworkVariableSettings settings, ISet value) : base(settings) + public NetworkSet(NetworkVariableReadPermission readPerm, ISet value) : base(readPerm) { m_Set = value; } @@ -66,7 +61,6 @@ public override void ResetDirty() { base.ResetDirty(); m_DirtyEvents.Clear(); - LastSyncedTime = NetworkBehaviour.NetworkManager.LocalTime; } /// @@ -440,14 +434,6 @@ public int LastModifiedTick return NetworkTickSystem.NoTick; } } - - private void EnsureInitialized() - { - if (NetworkBehaviour == null) - { - throw new InvalidOperationException("Cannot access " + nameof(NetworkSet) + " before it's initialized"); - } - } } /// diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index e631bdcef7..ebf3ed450f 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -23,28 +23,29 @@ public class NetworkVariable : NetworkVariableBase where T : unmanaged public OnValueChangedDelegate OnValueChanged; /// - /// Creates a NetworkVariable with the default value and settings + /// Creates a NetworkVariable with the default value and custom read permission /// - public NetworkVariable() { } + /// The read permission for the NetworkVariable + public NetworkVariable() {} /// - /// Creates a NetworkVariable with the default value and custom settings + /// Creates a NetworkVariable with the default value and custom read permission /// - /// The settings to use for the NetworkVariable - public NetworkVariable(NetworkVariableSettings settings) : base(settings) { } + /// The read permission for the NetworkVariable + public NetworkVariable(NetworkVariableReadPermission readPerm) : base(readPerm) {} /// /// Creates a NetworkVariable with a custom value and custom settings /// - /// The settings to use for the NetworkVariable + /// The read permission for the NetworkVariable /// The initial value to use for the NetworkVariable - public NetworkVariable(NetworkVariableSettings settings, T value) : base(settings) + public NetworkVariable(NetworkVariableReadPermission readPerm, T value) : base(readPerm) { m_InternalValue = value; } /// - /// Creates a NetworkVariable with a custom value and the default settings + /// Creates a NetworkVariable with a custom value and the default read permission /// /// The initial value to use for the NetworkVariable public NetworkVariable(T value) @@ -55,14 +56,6 @@ public NetworkVariable(T value) [SerializeField] private protected T m_InternalValue; - /// - /// The temporary accessor to enable struct element access until [MTT-1020] complete - /// - public ref T ValueRef - { - get => ref m_InternalValue; - } - /// /// The value of the NetworkVariable container /// @@ -76,7 +69,7 @@ public virtual T Value // Also, note this is not really very water-tight, if you are running as a host // we cannot tell if a NetworkVariable write is happening inside client-ish code - if (NetworkBehaviour && (NetworkBehaviour.NetworkManager.IsClient && !NetworkBehaviour.NetworkManager.IsHost)) + if (m_NetworkBehaviour && (m_NetworkBehaviour.NetworkManager.IsClient && !m_NetworkBehaviour.NetworkManager.IsHost)) { throw new InvalidOperationException("Client can't write to NetworkVariables"); } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs index 119dd88aa5..d80f51a1b1 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs @@ -1,4 +1,6 @@ +using System; using System.IO; +using UnityEditor.SceneManagement; namespace Unity.Netcode { @@ -7,23 +9,31 @@ namespace Unity.Netcode /// public abstract class NetworkVariableBase { + private protected NetworkBehaviour m_NetworkBehaviour; + + public void Initialize(NetworkBehaviour networkBehaviour) + { + m_NetworkBehaviour = networkBehaviour; + } /// /// The name of the channel to be used for syncing /// public const NetworkChannel NetworkVariableChannel = NetworkChannel.NetworkVariable; - protected NetworkVariableBase() { } - - protected NetworkVariableBase(NetworkVariableSettings settings) + protected NetworkVariableBase(NetworkVariableReadPermission readPermIn = NetworkVariableReadPermission.Everyone) { - Settings = settings; + ReadPerm = readPermIn; } - // demolish me - // or better setter? - internal protected NetworkBehaviour NetworkBehaviour { get; internal set; } + private protected void EnsureInitialized() + { + if (!m_NetworkBehaviour) + { + throw new InvalidOperationException("Cannot access NetworkVariable before it's initialized"); + } + } - private protected bool m_IsDirty = false; + private protected bool m_IsDirty; /// /// Gets or sets the name of the network variable's instance @@ -32,9 +42,9 @@ protected NetworkVariableBase(NetworkVariableSettings settings) public string Name { get; internal set; } /// - /// The settings for this var + /// The read permission for this var /// - public readonly NetworkVariableSettings Settings = new NetworkVariableSettings(); + public readonly NetworkVariableReadPermission ReadPerm; /// /// Sets whether or not the variable needs to be delta synced @@ -73,12 +83,12 @@ public virtual bool ShouldWrite(ulong clientId, bool isServer) /// Whether or not the client can read to the variable public bool CanClientRead(ulong clientId) { - switch (Settings.ReadPermission) + switch (ReadPerm) { case NetworkVariableReadPermission.Everyone: return true; case NetworkVariableReadPermission.OwnerOnly: - return NetworkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; } return true; } @@ -109,8 +119,6 @@ public virtual bool CanClientWrite(ulong clientId) /// Reads the complete state from the reader and applies it /// /// The stream to read the state from - /// The local network tick at which this var was written, on the machine it was written - /// The remote network tick at which this var was sent by the host public abstract void ReadField(Stream stream); /// @@ -118,8 +126,6 @@ public virtual bool CanClientWrite(ulong clientId) /// /// The stream to read the delta from /// Whether or not the delta should be kept as dirty or consumed - /// The local network tick at which this var was written, on the machine it was written - /// The remote network tick at which this var was sent by the host public abstract void ReadDelta(Stream stream, bool keepDirtyDelta); } } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs deleted file mode 100644 index 8bedabe0e3..0000000000 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace Unity.Netcode -{ - /// - /// Delegate type for permission checking - /// - /// The clientId whose permissions to check - public delegate bool NetworkVariablePermissionsDelegate(ulong clientId); - - /// - /// The settings class used by the build in NetworkVar implementations - /// - public class NetworkVariableSettings - { - /// - /// Defines the read permissions for this var - /// - public NetworkVariableReadPermission ReadPermission = NetworkVariableReadPermission.Everyone; - } -} diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs.meta b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs.meta deleted file mode 100644 index 00cacdb4cd..0000000000 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 06315503f26247d4aaa786326d12ecdc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs b/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs index 1e38683f7b..28d7d6b342 100644 --- a/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs +++ b/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs @@ -291,6 +291,12 @@ internal NetworkObject CreateLocalNetworkObject(bool isSceneObject, uint globalO // Ran on both server and client internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong? ownerClientId, Stream dataStream, bool readNetworkVariable, bool destroyWithScene) { + networkObject.IsSceneObject = sceneObject; + networkObject.NetworkObjectId = networkId; + networkObject.DestroyWithScene = sceneObject || destroyWithScene; + networkObject.OwnerClientIdInternal = ownerClientId; + networkObject.IsPlayerObject = playerObject; + if (networkObject == null) { throw new ArgumentNullException(nameof(networkObject), "Cannot spawn null object"); @@ -314,14 +320,6 @@ internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong netwo networkObject.IsSpawned = true; - networkObject.IsSceneObject = sceneObject; - networkObject.NetworkObjectId = networkId; - - networkObject.DestroyWithScene = sceneObject || destroyWithScene; - - networkObject.OwnerClientIdInternal = ownerClientId; - networkObject.IsPlayerObject = playerObject; - SpawnedObjects.Add(networkObject.NetworkObjectId, networkObject); SpawnedObjectsList.Add(networkObject); diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs index 5115083e18..96d11b32cd 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs @@ -84,14 +84,14 @@ private void InitializeTest() // NetworkVariable Value Type Constructor Test Coverage m_NetworkVariableBool = new NetworkVariable(true); - m_NetworkVariableByte = new NetworkVariable(0); + m_NetworkVariableByte = new NetworkVariable((byte)0); m_NetworkVariableColor = new NetworkVariable(new Color(1, 1, 1, 1)); m_NetworkVariableColor32 = new NetworkVariable(new Color32(1, 1, 1, 1)); m_NetworkVariableDouble = new NetworkVariable(1.0); m_NetworkVariableFloat = new NetworkVariable(1.0f); m_NetworkVariableInt = new NetworkVariable(1); m_NetworkVariableLong = new NetworkVariable(1); - m_NetworkVariableSByte = new NetworkVariable(0); + m_NetworkVariableSByte = new NetworkVariable((sbyte)0); m_NetworkVariableQuaternion = new NetworkVariable(Quaternion.identity); m_NetworkVariableShort = new NetworkVariable(256); m_NetworkVariableVector4 = new NetworkVariable(new Vector4(1, 1, 1, 1)); @@ -102,49 +102,45 @@ private void InitializeTest() m_NetworkVariableUInt = new NetworkVariable(1); m_NetworkVariableUShort = new NetworkVariable(1); - - // NetworkVariable NetworkVariableSettings Constructor Test Coverage - var settings = new NetworkVariableSettings(); - settings.ReadPermission = NetworkVariableReadPermission.Everyone; - m_NetworkVariableBool = new NetworkVariable(settings); - m_NetworkVariableByte = new NetworkVariable(settings); - m_NetworkVariableColor = new NetworkVariable(settings); - m_NetworkVariableColor32 = new NetworkVariable(settings); - m_NetworkVariableDouble = new NetworkVariable(settings); - m_NetworkVariableFloat = new NetworkVariable(settings); - m_NetworkVariableInt = new NetworkVariable(settings); - m_NetworkVariableLong = new NetworkVariable(settings); - m_NetworkVariableSByte = new NetworkVariable(settings); - m_NetworkVariableQuaternion = new NetworkVariable(settings); - m_NetworkVariableShort = new NetworkVariable(settings); - m_NetworkVariableVector4 = new NetworkVariable(settings); - m_NetworkVariableVector3 = new NetworkVariable(settings); - m_NetworkVariableVector2 = new NetworkVariable(settings); - m_NetworkVariableRay = new NetworkVariable(settings); - m_NetworkVariableULong = new NetworkVariable(settings); - m_NetworkVariableUInt = new NetworkVariable(settings); - m_NetworkVariableUShort = new NetworkVariable(settings); + m_NetworkVariableBool = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableByte = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableColor = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableColor32 = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableDouble = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableFloat = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableInt = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableLong = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableSByte = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableQuaternion = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableShort = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableVector4 = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableVector3 = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableVector2 = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableRay = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableULong = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableUInt = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableUShort = new NetworkVariable(NetworkVariableReadPermission.Everyone); // NetworkVariable Value Type and NetworkVariableSettings Constructor Test Coverage - m_NetworkVariableBool = new NetworkVariable(settings, true); - m_NetworkVariableByte = new NetworkVariable(settings, 0); - m_NetworkVariableColor = new NetworkVariable(settings, new Color(1, 1, 1, 1)); - m_NetworkVariableColor32 = new NetworkVariable(settings, new Color32(1, 1, 1, 1)); - m_NetworkVariableDouble = new NetworkVariable(settings, 1.0); - m_NetworkVariableFloat = new NetworkVariable(settings, 1.0f); - m_NetworkVariableInt = new NetworkVariable(settings, 1); - m_NetworkVariableLong = new NetworkVariable(settings, 1); - m_NetworkVariableSByte = new NetworkVariable(settings, 0); - m_NetworkVariableQuaternion = new NetworkVariable(settings, Quaternion.identity); - m_NetworkVariableShort = new NetworkVariable(settings, 1); - m_NetworkVariableVector4 = new NetworkVariable(settings, new Vector4(1, 1, 1, 1)); - m_NetworkVariableVector3 = new NetworkVariable(settings, new Vector3(1, 1, 1)); - m_NetworkVariableVector2 = new NetworkVariable(settings, new Vector2(1, 1)); - m_NetworkVariableRay = new NetworkVariable(settings, new Ray()); - m_NetworkVariableULong = new NetworkVariable(settings, 1); - m_NetworkVariableUInt = new NetworkVariable(settings, 1); - m_NetworkVariableUShort = new NetworkVariable(settings, 1); + m_NetworkVariableBool = new NetworkVariable(NetworkVariableReadPermission.Everyone, true); + m_NetworkVariableByte = new NetworkVariable(NetworkVariableReadPermission.Everyone, 0); + m_NetworkVariableColor = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Color(1, 1, 1, 1)); + m_NetworkVariableColor32 = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Color32(1, 1, 1, 1)); + m_NetworkVariableDouble = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1.0); + m_NetworkVariableFloat = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1.0f); + m_NetworkVariableInt = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); + m_NetworkVariableLong = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); + m_NetworkVariableSByte = new NetworkVariable(NetworkVariableReadPermission.Everyone, 0); + m_NetworkVariableQuaternion = new NetworkVariable(NetworkVariableReadPermission.Everyone, Quaternion.identity); + m_NetworkVariableShort = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); + m_NetworkVariableVector4 = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Vector4(1, 1, 1, 1)); + m_NetworkVariableVector3 = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Vector3(1, 1, 1)); + m_NetworkVariableVector2 = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Vector2(1, 1)); + m_NetworkVariableRay = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Ray()); + m_NetworkVariableULong = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); + m_NetworkVariableUInt = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); + m_NetworkVariableUShort = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); // Use this nifty class: NetworkVariableHelper // Tracks if NetworkVariable changed invokes the OnValueChanged callback for the given instance type diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs index 60a5f0e3be..25f9068cf2 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs @@ -22,7 +22,7 @@ public class NetworkVariableTest : NetworkBehaviour public readonly ClientNetworkVariable ClientVar = new ClientNetworkVariable(); public readonly ClientNetworkVariable ClientVarPrivate = - new ClientNetworkVariable(new NetworkVariableSettings { ReadPermission = NetworkVariableReadPermission.OwnerOnly }); + new ClientNetworkVariable(NetworkVariableReadPermission.OwnerOnly); public readonly NetworkVariable TheScalar = new NetworkVariable(); public readonly NetworkList TheList = new NetworkList(); From abfcfc02171043b74af3caee56f9c8755906cb90 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Thu, 26 Aug 2021 12:49:26 -0700 Subject: [PATCH 2/8] remove ensure initialized --- .../Runtime/Core/NetworkBehaviour.cs | 18 ++++++++++-------- .../Messaging/InternalMessageHandler.cs | 6 +++--- .../Collections/NetworkDictionary.cs | 7 ------- .../NetworkVariable/Collections/NetworkList.cs | 6 ------ .../NetworkVariable/Collections/NetworkSet.cs | 7 ------- .../NetworkVariable/NetworkVariableBase.cs | 8 -------- 6 files changed, 13 insertions(+), 39 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index bb379d50f2..ef4d24462f 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -624,7 +624,7 @@ private bool CouldHaveDirtyNetworkVariables() return false; } - internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, NetworkBehaviour logInstance) + internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -656,7 +656,7 @@ internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, Network { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + NetworkLog.LogWarning($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. => {nameof(NetworkObjectId)}: {NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {NetworkObject.GetNetworkBehaviourOrderIndex(this)} - VariableIndex: {i}"); NetworkLog.LogError($"[{NetworkVariableFields[i].GetType().Name}]"); } @@ -673,7 +673,7 @@ internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, Network // - TwoTen if (NetworkLog.CurrentLogLevel <= LogLevel.Error) { - NetworkLog.LogError($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. No more variables can be read. This is critical. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + NetworkLog.LogError($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. No more variables can be read. This is critical. => {nameof(NetworkObjectId)}: {NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {NetworkObject.GetNetworkBehaviourOrderIndex(this)} - VariableIndex: {i}"); NetworkLog.LogError($"[{NetworkVariableFields[i].GetType().Name}]"); } @@ -684,10 +684,10 @@ internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, Network NetworkVariableFields[i].ReadDelta(stream, NetworkManager.IsServer); NetworkManager.NetworkMetrics.TrackNetworkVariableDeltaReceived( clientId, - logInstance.NetworkObjectId, - logInstance.name, + NetworkObjectId, + name, NetworkVariableFields[i].Name, - logInstance.__getTypeName(), + __getTypeName(), stream.Length); (stream as NetworkBuffer).SkipPadBits(); @@ -698,7 +698,8 @@ internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, Network { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning($"Var delta read too far. {stream.Position - (readStartPos + varSize)} bytes. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + NetworkLog.LogWarning( + $"Var delta read too far. {stream.Position - (readStartPos + varSize)} bytes. => {nameof(NetworkObjectId)}: {NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {NetworkObject.GetNetworkBehaviourOrderIndex(this)} - VariableIndex: {i}"); } stream.Position = readStartPos + varSize; @@ -707,7 +708,8 @@ internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, Network { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning($"Var delta read too little. {(readStartPos + varSize) - stream.Position} bytes. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + NetworkLog.LogWarning( + $"Var delta read too little. {(readStartPos + varSize) - stream.Position} bytes. => {nameof(NetworkObjectId)}: {NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {NetworkObject.GetNetworkBehaviourOrderIndex(this)} - VariableIndex: {i}"); } stream.Position = readStartPos + varSize; diff --git a/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs b/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs index fd4249c65c..cd89b1f8e7 100644 --- a/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs +++ b/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs @@ -211,9 +211,9 @@ public void HandleNetworkVariableDelta(ulong clientId, Stream stream) if (NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(networkObjectId, out NetworkObject networkObject)) { - NetworkBehaviour instance = networkObject.GetNetworkBehaviourAtOrderIndex(networkBehaviourIndex); + NetworkBehaviour behaviour = networkObject.GetNetworkBehaviourAtOrderIndex(networkBehaviourIndex); - if (instance == null) + if (behaviour == null) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { @@ -222,7 +222,7 @@ public void HandleNetworkVariableDelta(ulong clientId, Stream stream) } else { - instance.HandleNetworkVariableDeltas(stream, clientId, instance); + behaviour.HandleNetworkVariableDeltas(stream, clientId); } } else if (NetworkManager.IsServer) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 6adde145b5..43d224ffc9 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -303,8 +303,6 @@ public TValue this[TKey key] get => m_Dictionary[key]; set { - EnsureInitialized(); - m_Dictionary[key] = value; var dictionaryEvent = new NetworkDictionaryEvent() @@ -334,7 +332,6 @@ public TValue this[TKey key] /// public void Add(TKey key, TValue value) { - EnsureInitialized(); m_Dictionary.Add(key, value); var dictionaryEvent = new NetworkDictionaryEvent() @@ -350,7 +347,6 @@ public void Add(TKey key, TValue value) /// public void Add(KeyValuePair item) { - EnsureInitialized(); m_Dictionary.Add(item); var dictionaryEvent = new NetworkDictionaryEvent() @@ -366,7 +362,6 @@ public void Add(KeyValuePair item) /// public void Clear() { - EnsureInitialized(); m_Dictionary.Clear(); var dictionaryEvent = new NetworkDictionaryEvent() @@ -404,7 +399,6 @@ public IEnumerator> GetEnumerator() /// public bool Remove(TKey key) { - EnsureInitialized(); m_Dictionary.Remove(key); TValue value; @@ -426,7 +420,6 @@ public bool Remove(TKey key) /// public bool Remove(KeyValuePair item) { - EnsureInitialized(); m_Dictionary.Remove(item); var dictionaryEvent = new NetworkDictionaryEvent() diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index 74acdabf05..67d2207901 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -332,7 +332,6 @@ IEnumerator IEnumerable.GetEnumerator() /// public void Add(T item) { - EnsureInitialized(); m_List.Add(item); var listEvent = new NetworkListEvent() @@ -348,7 +347,6 @@ public void Add(T item) /// public void Clear() { - EnsureInitialized(); m_List.Clear(); var listEvent = new NetworkListEvent() @@ -374,7 +372,6 @@ public void CopyTo(T[] array, int arrayIndex) /// public bool Remove(T item) { - EnsureInitialized(); m_List.Remove(item); var listEvent = new NetworkListEvent() @@ -402,7 +399,6 @@ public int IndexOf(T item) /// public void Insert(int index, T item) { - EnsureInitialized(); m_List.Insert(index, item); var listEvent = new NetworkListEvent() @@ -418,7 +414,6 @@ public void Insert(int index, T item) /// public void RemoveAt(int index) { - EnsureInitialized(); m_List.RemoveAt(index); var listEvent = new NetworkListEvent() @@ -437,7 +432,6 @@ public T this[int index] get => m_List[index]; set { - EnsureInitialized(); m_List[index] = value; var listEvent = new NetworkListEvent() diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index b689a19238..58ba209494 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -293,8 +293,6 @@ public bool SetEquals(IEnumerable other) /// public void SymmetricExceptWith(IEnumerable other) { - EnsureInitialized(); - foreach (T value in other) { if (m_Set.Contains(value)) @@ -323,8 +321,6 @@ public void SymmetricExceptWith(IEnumerable other) /// public void UnionWith(IEnumerable other) { - EnsureInitialized(); - foreach (T value in other) { if (!m_Set.Contains(value)) @@ -348,7 +344,6 @@ public void UnionWith(IEnumerable other) public bool Add(T item) { - EnsureInitialized(); m_Set.Add(item); var setEvent = new NetworkSetEvent() @@ -372,7 +367,6 @@ public bool Add(T item) /// public void Clear() { - EnsureInitialized(); m_Set.Clear(); var setEvent = new NetworkSetEvent() @@ -402,7 +396,6 @@ public void CopyTo(T[] array, int arrayIndex) /// public bool Remove(T item) { - EnsureInitialized(); m_Set.Remove(item); var setEvent = new NetworkSetEvent() diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs index d80f51a1b1..e11a8ece2e 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs @@ -25,14 +25,6 @@ protected NetworkVariableBase(NetworkVariableReadPermission readPermIn = Network ReadPerm = readPermIn; } - private protected void EnsureInitialized() - { - if (!m_NetworkBehaviour) - { - throw new InvalidOperationException("Cannot access NetworkVariable before it's initialized"); - } - } - private protected bool m_IsDirty; /// From a0495399bce2e5d724558561ec127f232450ccca Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Thu, 26 Aug 2021 13:17:59 -0700 Subject: [PATCH 3/8] moved init, removed unused var --- .../Runtime/Core/NetworkObject.cs | 4 ++-- .../Runtime/Spawning/NetworkSpawnManager.cs | 23 +++++++++++++------ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs index 53d16f0b9a..134582b259 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs @@ -241,7 +241,7 @@ public void NetworkShow(ulong clientId) Observers.Add(clientId); - NetworkManager.SpawnManager.SendSpawnCallForObject(clientId, OwnerClientId, this); + NetworkManager.SpawnManager.SendSpawnCallForObject(clientId, this); } /// @@ -499,7 +499,7 @@ private void SpawnInternal(bool destroyWithScene, ulong? ownerClientId, bool pla { if (Observers.Contains(NetworkManager.ConnectedClientsList[i].ClientId)) { - NetworkManager.SpawnManager.SendSpawnCallForObject(NetworkManager.ConnectedClientsList[i].ClientId, ownerId, this); + NetworkManager.SpawnManager.SendSpawnCallForObject(NetworkManager.ConnectedClientsList[i].ClientId, this); } } } diff --git a/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs b/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs index 28d7d6b342..7402a5bd07 100644 --- a/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs +++ b/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs @@ -291,12 +291,6 @@ internal NetworkObject CreateLocalNetworkObject(bool isSceneObject, uint globalO // Ran on both server and client internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong? ownerClientId, Stream dataStream, bool readNetworkVariable, bool destroyWithScene) { - networkObject.IsSceneObject = sceneObject; - networkObject.NetworkObjectId = networkId; - networkObject.DestroyWithScene = sceneObject || destroyWithScene; - networkObject.OwnerClientIdInternal = ownerClientId; - networkObject.IsPlayerObject = playerObject; - if (networkObject == null) { throw new ArgumentNullException(nameof(networkObject), "Cannot spawn null object"); @@ -318,8 +312,23 @@ internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong netwo return; } + // this initialization really should be at the bottom of the function networkObject.IsSpawned = true; + // this initialization really should be at the top of this function. If and when we break the + // NetworkVariable dependency on NetworkBehaviour, this otherwise creates problems because + // SetNetworkVariableData above calls InitializeVariables, and the 'baked out' data isn't ready there; + // the current design banks on getting the network behaviour set and then only reading from it + // after the below initialization code. However cowardice compels me to hold off on moving this until + // that commit + networkObject.IsSceneObject = sceneObject; + networkObject.NetworkObjectId = networkId; + + networkObject.DestroyWithScene = sceneObject || destroyWithScene; + + networkObject.OwnerClientIdInternal = ownerClientId; + networkObject.IsPlayerObject = playerObject; + SpawnedObjects.Add(networkObject.NetworkObjectId, networkObject); SpawnedObjectsList.Add(networkObject); @@ -361,7 +370,7 @@ internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong netwo networkObject.InvokeBehaviourNetworkSpawn(); } - internal void SendSpawnCallForObject(ulong clientId, ulong ownerClientId, NetworkObject networkObject) + internal void SendSpawnCallForObject(ulong clientId, NetworkObject networkObject) { if (!NetworkManager.NetworkConfig.UseSnapshotSpawn) { From 705ec492d5a519ae0c6b9969be711b9fa98e0e1c Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Wed, 25 Aug 2021 16:57:48 -0700 Subject: [PATCH 4/8] refactor!: remove network variable settings, network behaviour cleanup --- .../Runtime/Core/NetworkBehaviour.cs | 52 ++++++------ .../Runtime/Core/NetworkObject.cs | 10 ++- .../Messaging/InternalMessageHandler.cs | 2 +- .../NetworkVariable/ClientNetworkVariable.cs | 8 +- .../Collections/NetworkDictionary.cs | 22 ++--- .../Collections/NetworkList.cs | 28 ++----- .../NetworkVariable/Collections/NetworkSet.cs | 18 +---- .../NetworkVariable/NetworkVariable.cs | 27 +++---- .../NetworkVariable/NetworkVariableBase.cs | 38 +++++---- .../NetworkVariableSettings.cs | 19 ----- .../NetworkVariableSettings.cs.meta | 11 --- .../Runtime/Spawning/NetworkSpawnManager.cs | 14 ++-- .../NetworkVariableTestComponent.cs | 80 +++++++++---------- .../Tests/Runtime/NetworkVariableTests.cs | 2 +- 14 files changed, 126 insertions(+), 205 deletions(-) delete mode 100644 com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs delete mode 100644 com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs.meta diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index d871509288..bb379d50f2 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -425,7 +425,7 @@ internal void InitializeVariables() sortedFields[i].SetValue(this, instance); } - instance.NetworkBehaviour = this; + instance.Initialize(this); var instanceNameProperty = fieldType.GetProperty(nameof(NetworkVariableBase.Name)); var sanitizedVariableName = sortedFields[i].Name.Replace("<", string.Empty).Replace(">k__BackingField", string.Empty); @@ -624,15 +624,15 @@ private bool CouldHaveDirtyNetworkVariables() return false; } - internal static void HandleNetworkVariableDeltas(List networkVariableList, Stream stream, ulong clientId, NetworkBehaviour logInstance, NetworkManager networkManager) + internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, NetworkBehaviour logInstance) { using (var reader = PooledNetworkReader.Get(stream)) { - for (int i = 0; i < networkVariableList.Count; i++) + for (int i = 0; i < NetworkVariableFields.Count; i++) { ushort varSize = 0; - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { varSize = reader.ReadUInt16Packed(); @@ -649,15 +649,15 @@ internal static void HandleNetworkVariableDeltas(List netwo } } - if (networkManager.IsServer && !networkVariableList[i].CanClientWrite(clientId)) + if (NetworkManager.IsServer && !NetworkVariableFields[i].CanClientWrite(clientId)) { // we are choosing not to fire an exception here, because otherwise a malicious client could use this to crash the server - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { NetworkLog.LogWarning($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); - NetworkLog.LogError($"[{networkVariableList[i].GetType().Name}]"); + NetworkLog.LogError($"[{NetworkVariableFields[i].GetType().Name}]"); } stream.Position += varSize; @@ -674,25 +674,25 @@ internal static void HandleNetworkVariableDeltas(List netwo if (NetworkLog.CurrentLogLevel <= LogLevel.Error) { NetworkLog.LogError($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. No more variables can be read. This is critical. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); - NetworkLog.LogError($"[{networkVariableList[i].GetType().Name}]"); + NetworkLog.LogError($"[{NetworkVariableFields[i].GetType().Name}]"); } return; } long readStartPos = stream.Position; - networkVariableList[i].ReadDelta(stream, networkManager.IsServer); - networkManager.NetworkMetrics.TrackNetworkVariableDeltaReceived( + NetworkVariableFields[i].ReadDelta(stream, NetworkManager.IsServer); + NetworkManager.NetworkMetrics.TrackNetworkVariableDeltaReceived( clientId, logInstance.NetworkObjectId, logInstance.name, - networkVariableList[i].Name, + NetworkVariableFields[i].Name, logInstance.__getTypeName(), stream.Length); (stream as NetworkBuffer).SkipPadBits(); - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (stream.Position > (readStartPos + varSize)) { @@ -717,20 +717,20 @@ internal static void HandleNetworkVariableDeltas(List netwo } } - internal static void WriteNetworkVariableData(List networkVariableList, Stream stream, ulong clientId, NetworkManager networkManager) + internal void WriteNetworkVariableData(Stream stream, ulong clientId) { - if (networkVariableList.Count == 0) + if (NetworkVariableFields.Count == 0) { return; } using (var writer = PooledNetworkWriter.Get(stream)) { - for (int j = 0; j < networkVariableList.Count; j++) + for (int j = 0; j < NetworkVariableFields.Count; j++) { - bool canClientRead = networkVariableList[j].CanClientRead(clientId); + bool canClientRead = NetworkVariableFields[j].CanClientRead(clientId); - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (!canClientRead) { @@ -744,11 +744,11 @@ internal static void WriteNetworkVariableData(List networkV if (canClientRead) { - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { using (var varBuffer = PooledNetworkBuffer.Get()) { - networkVariableList[j].WriteField(varBuffer); + NetworkVariableFields[j].WriteField(varBuffer); varBuffer.PadBuffer(); writer.WriteUInt16Packed((ushort)varBuffer.Length); @@ -757,7 +757,7 @@ internal static void WriteNetworkVariableData(List networkV } else { - networkVariableList[j].WriteField(stream); + NetworkVariableFields[j].WriteField(stream); writer.WritePadBits(); } } @@ -765,20 +765,20 @@ internal static void WriteNetworkVariableData(List networkV } } - internal static void SetNetworkVariableData(List networkVariableList, Stream stream, NetworkManager networkManager) + internal void SetNetworkVariableData(Stream stream) { - if (networkVariableList.Count == 0) + if (NetworkVariableFields.Count == 0) { return; } using (var reader = PooledNetworkReader.Get(stream)) { - for (int j = 0; j < networkVariableList.Count; j++) + for (int j = 0; j < NetworkVariableFields.Count; j++) { ushort varSize = 0; - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { varSize = reader.ReadUInt16Packed(); @@ -797,10 +797,10 @@ internal static void SetNetworkVariableData(List networkVar long readStartPos = stream.Position; - networkVariableList[j].ReadField(stream); + NetworkVariableFields[j].ReadField(stream); reader.SkipPadBits(); - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (stream is NetworkBuffer networkBuffer) { diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs index 9b60dc3862..53d16f0b9a 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs @@ -872,8 +872,9 @@ internal void WriteNetworkVariableData(Stream stream, ulong clientId) { for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { - ChildNetworkBehaviours[i].InitializeVariables(); - NetworkBehaviour.WriteNetworkVariableData(ChildNetworkBehaviours[i].NetworkVariableFields, stream, clientId, NetworkManager); + var behavior = ChildNetworkBehaviours[i]; + behavior.InitializeVariables(); + behavior.WriteNetworkVariableData(stream, clientId); } } @@ -881,8 +882,9 @@ internal void SetNetworkVariableData(Stream stream) { for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { - ChildNetworkBehaviours[i].InitializeVariables(); - NetworkBehaviour.SetNetworkVariableData(ChildNetworkBehaviours[i].NetworkVariableFields, stream, NetworkManager); + var behaviour = ChildNetworkBehaviours[i]; + behaviour.InitializeVariables(); + behaviour.SetNetworkVariableData(stream); } } diff --git a/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs b/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs index 6bce802f67..fd4249c65c 100644 --- a/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs +++ b/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs @@ -222,7 +222,7 @@ public void HandleNetworkVariableDelta(ulong clientId, Stream stream) } else { - NetworkBehaviour.HandleNetworkVariableDeltas(instance.NetworkVariableFields, stream, clientId, instance, NetworkManager); + instance.HandleNetworkVariableDeltas(stream, clientId, instance); } } else if (NetworkManager.IsServer) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs index 6d5c5e03f1..e187741189 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs @@ -15,16 +15,16 @@ public class ClientNetworkVariable : NetworkVariable where T : unmanaged { public ClientNetworkVariable() { } - public ClientNetworkVariable(NetworkVariableSettings settings) : base(settings) { } + public ClientNetworkVariable(NetworkVariableReadPermission readPerm) : base(readPerm) { } public override bool CanClientWrite(ulong clientId) { - return NetworkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; } public override bool ShouldWrite(ulong clientId, bool isServer) { - return m_IsDirty && !isServer && NetworkBehaviour.IsOwner; + return m_IsDirty && !isServer && m_NetworkBehaviour.IsOwner; } /// @@ -40,7 +40,7 @@ public override T Value // Also, note this is not really very water-tight, if you are running as a host // we cannot tell if a ClientNetworkVariable write is happening inside server-ish code - if (NetworkBehaviour.NetworkManager.IsServer) + if (m_NetworkBehaviour.NetworkManager.IsServer) { throw new InvalidOperationException("Server not allowed to write to ClientNetworkVariables"); } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 5e533124f5..6adde145b5 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -34,15 +34,15 @@ public NetworkDictionary() { } /// /// Creates a NetworkDictionary with the default value and custom settings /// - /// The settings to use for the NetworkDictionary - public NetworkDictionary(NetworkVariableSettings settings) : base(settings) { } + /// The read permission to use for this NetworkDictionary + public NetworkDictionary(NetworkVariableReadPermission readPerm) : base(readPerm) { } /// /// Creates a NetworkDictionary with a custom value and custom settings /// - /// The settings to use for the NetworkDictionary + /// The read permission to use for this NetworkDictionary /// The initial value to use for the NetworkDictionary - public NetworkDictionary(NetworkVariableSettings settings, IDictionary value) : base(settings) + public NetworkDictionary(NetworkVariableReadPermission readPerm, IDictionary value) : base(readPerm) { m_Dictionary = value; } @@ -448,11 +448,7 @@ IEnumerator IEnumerable.GetEnumerator() private void HandleAddDictionaryEvent(NetworkDictionaryEvent dictionaryEvent) { - if (NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) - { - m_DirtyEvents.Add(dictionaryEvent); - } - + m_DirtyEvents.Add(dictionaryEvent); OnDictionaryChanged?.Invoke(dictionaryEvent); } @@ -464,14 +460,6 @@ public int LastModifiedTick return NetworkTickSystem.NoTick; } } - - private void EnsureInitialized() - { - if (NetworkBehaviour == null) - { - throw new InvalidOperationException("Cannot access " + nameof(NetworkDictionary) + " before it's initialized"); - } - } } /// diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index e19dc4eaa0..74acdabf05 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -14,11 +14,6 @@ public class NetworkList : NetworkVariableBase, IList where T : unmanaged private readonly IList m_List = new List(); private readonly List> m_DirtyEvents = new List>(); - /// - /// Gets the last time the variable was synced - /// - public NetworkTime LastSyncedTime { get; internal set; } - /// /// Delegate type for list changed event /// @@ -38,15 +33,15 @@ public NetworkList() { } /// /// Creates a NetworkList with the default value and custom settings /// - /// The settings to use for the NetworkList - public NetworkList(NetworkVariableSettings settings) : base(settings) { } + /// The read permission to use for the NetworkList + public NetworkList(NetworkVariableReadPermission readPerm) : base(readPerm) { } /// /// Creates a NetworkList with a custom value and custom settings /// - /// The settings to use for the NetworkList + /// The read permission to use for the NetworkList /// The initial value to use for the NetworkList - public NetworkList(NetworkVariableSettings settings, IList value) : base(settings) + public NetworkList(NetworkVariableReadPermission readPerm, IList value) : base(readPerm) { m_List = value; } @@ -65,7 +60,6 @@ public override void ResetDirty() { base.ResetDirty(); m_DirtyEvents.Clear(); - LastSyncedTime = NetworkBehaviour.NetworkManager.LocalTime; } /// @@ -459,11 +453,7 @@ public T this[int index] private void HandleAddListEvent(NetworkListEvent listEvent) { - if (NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) - { - m_DirtyEvents.Add(listEvent); - } - + m_DirtyEvents.Add(listEvent); OnListChanged?.Invoke(listEvent); } @@ -475,14 +465,6 @@ public int LastModifiedTick return NetworkTickSystem.NoTick; } } - - private void EnsureInitialized() - { - if (NetworkBehaviour == null) - { - throw new InvalidOperationException("Cannot access " + nameof(NetworkList) + " before it's initialized"); - } - } } /// diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index 865e8f45fc..b689a19238 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -15,11 +15,6 @@ public class NetworkSet : NetworkVariableBase, ISet where T: unmanaged private readonly ISet m_Set = new HashSet(); private readonly List> m_DirtyEvents = new List>(); - /// - /// Gets the last time the variable was synced - /// - public NetworkTime LastSyncedTime { get; internal set; } - /// /// Delegate type for set changed event /// @@ -40,14 +35,14 @@ public NetworkSet() { } /// Creates a NetworkSet with the default value and custom settings /// /// The settings to use for the NetworkList - public NetworkSet(NetworkVariableSettings settings) : base(settings) { } + public NetworkSet(NetworkVariableReadPermission readPerm) : base(readPerm) { } /// /// Creates a NetworkSet with a custom value and custom settings /// /// The settings to use for the NetworkSet /// The initial value to use for the NetworkSet - public NetworkSet(NetworkVariableSettings settings, ISet value) : base(settings) + public NetworkSet(NetworkVariableReadPermission readPerm, ISet value) : base(readPerm) { m_Set = value; } @@ -66,7 +61,6 @@ public override void ResetDirty() { base.ResetDirty(); m_DirtyEvents.Clear(); - LastSyncedTime = NetworkBehaviour.NetworkManager.LocalTime; } /// @@ -440,14 +434,6 @@ public int LastModifiedTick return NetworkTickSystem.NoTick; } } - - private void EnsureInitialized() - { - if (NetworkBehaviour == null) - { - throw new InvalidOperationException("Cannot access " + nameof(NetworkSet) + " before it's initialized"); - } - } } /// diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index e631bdcef7..ebf3ed450f 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -23,28 +23,29 @@ public class NetworkVariable : NetworkVariableBase where T : unmanaged public OnValueChangedDelegate OnValueChanged; /// - /// Creates a NetworkVariable with the default value and settings + /// Creates a NetworkVariable with the default value and custom read permission /// - public NetworkVariable() { } + /// The read permission for the NetworkVariable + public NetworkVariable() {} /// - /// Creates a NetworkVariable with the default value and custom settings + /// Creates a NetworkVariable with the default value and custom read permission /// - /// The settings to use for the NetworkVariable - public NetworkVariable(NetworkVariableSettings settings) : base(settings) { } + /// The read permission for the NetworkVariable + public NetworkVariable(NetworkVariableReadPermission readPerm) : base(readPerm) {} /// /// Creates a NetworkVariable with a custom value and custom settings /// - /// The settings to use for the NetworkVariable + /// The read permission for the NetworkVariable /// The initial value to use for the NetworkVariable - public NetworkVariable(NetworkVariableSettings settings, T value) : base(settings) + public NetworkVariable(NetworkVariableReadPermission readPerm, T value) : base(readPerm) { m_InternalValue = value; } /// - /// Creates a NetworkVariable with a custom value and the default settings + /// Creates a NetworkVariable with a custom value and the default read permission /// /// The initial value to use for the NetworkVariable public NetworkVariable(T value) @@ -55,14 +56,6 @@ public NetworkVariable(T value) [SerializeField] private protected T m_InternalValue; - /// - /// The temporary accessor to enable struct element access until [MTT-1020] complete - /// - public ref T ValueRef - { - get => ref m_InternalValue; - } - /// /// The value of the NetworkVariable container /// @@ -76,7 +69,7 @@ public virtual T Value // Also, note this is not really very water-tight, if you are running as a host // we cannot tell if a NetworkVariable write is happening inside client-ish code - if (NetworkBehaviour && (NetworkBehaviour.NetworkManager.IsClient && !NetworkBehaviour.NetworkManager.IsHost)) + if (m_NetworkBehaviour && (m_NetworkBehaviour.NetworkManager.IsClient && !m_NetworkBehaviour.NetworkManager.IsHost)) { throw new InvalidOperationException("Client can't write to NetworkVariables"); } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs index 119dd88aa5..d80f51a1b1 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs @@ -1,4 +1,6 @@ +using System; using System.IO; +using UnityEditor.SceneManagement; namespace Unity.Netcode { @@ -7,23 +9,31 @@ namespace Unity.Netcode /// public abstract class NetworkVariableBase { + private protected NetworkBehaviour m_NetworkBehaviour; + + public void Initialize(NetworkBehaviour networkBehaviour) + { + m_NetworkBehaviour = networkBehaviour; + } /// /// The name of the channel to be used for syncing /// public const NetworkChannel NetworkVariableChannel = NetworkChannel.NetworkVariable; - protected NetworkVariableBase() { } - - protected NetworkVariableBase(NetworkVariableSettings settings) + protected NetworkVariableBase(NetworkVariableReadPermission readPermIn = NetworkVariableReadPermission.Everyone) { - Settings = settings; + ReadPerm = readPermIn; } - // demolish me - // or better setter? - internal protected NetworkBehaviour NetworkBehaviour { get; internal set; } + private protected void EnsureInitialized() + { + if (!m_NetworkBehaviour) + { + throw new InvalidOperationException("Cannot access NetworkVariable before it's initialized"); + } + } - private protected bool m_IsDirty = false; + private protected bool m_IsDirty; /// /// Gets or sets the name of the network variable's instance @@ -32,9 +42,9 @@ protected NetworkVariableBase(NetworkVariableSettings settings) public string Name { get; internal set; } /// - /// The settings for this var + /// The read permission for this var /// - public readonly NetworkVariableSettings Settings = new NetworkVariableSettings(); + public readonly NetworkVariableReadPermission ReadPerm; /// /// Sets whether or not the variable needs to be delta synced @@ -73,12 +83,12 @@ public virtual bool ShouldWrite(ulong clientId, bool isServer) /// Whether or not the client can read to the variable public bool CanClientRead(ulong clientId) { - switch (Settings.ReadPermission) + switch (ReadPerm) { case NetworkVariableReadPermission.Everyone: return true; case NetworkVariableReadPermission.OwnerOnly: - return NetworkBehaviour.OwnerClientId == clientId; + return m_NetworkBehaviour.OwnerClientId == clientId; } return true; } @@ -109,8 +119,6 @@ public virtual bool CanClientWrite(ulong clientId) /// Reads the complete state from the reader and applies it /// /// The stream to read the state from - /// The local network tick at which this var was written, on the machine it was written - /// The remote network tick at which this var was sent by the host public abstract void ReadField(Stream stream); /// @@ -118,8 +126,6 @@ public virtual bool CanClientWrite(ulong clientId) /// /// The stream to read the delta from /// Whether or not the delta should be kept as dirty or consumed - /// The local network tick at which this var was written, on the machine it was written - /// The remote network tick at which this var was sent by the host public abstract void ReadDelta(Stream stream, bool keepDirtyDelta); } } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs deleted file mode 100644 index 8bedabe0e3..0000000000 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace Unity.Netcode -{ - /// - /// Delegate type for permission checking - /// - /// The clientId whose permissions to check - public delegate bool NetworkVariablePermissionsDelegate(ulong clientId); - - /// - /// The settings class used by the build in NetworkVar implementations - /// - public class NetworkVariableSettings - { - /// - /// Defines the read permissions for this var - /// - public NetworkVariableReadPermission ReadPermission = NetworkVariableReadPermission.Everyone; - } -} diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs.meta b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs.meta deleted file mode 100644 index 00cacdb4cd..0000000000 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 06315503f26247d4aaa786326d12ecdc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs b/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs index 1e38683f7b..28d7d6b342 100644 --- a/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs +++ b/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs @@ -291,6 +291,12 @@ internal NetworkObject CreateLocalNetworkObject(bool isSceneObject, uint globalO // Ran on both server and client internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong? ownerClientId, Stream dataStream, bool readNetworkVariable, bool destroyWithScene) { + networkObject.IsSceneObject = sceneObject; + networkObject.NetworkObjectId = networkId; + networkObject.DestroyWithScene = sceneObject || destroyWithScene; + networkObject.OwnerClientIdInternal = ownerClientId; + networkObject.IsPlayerObject = playerObject; + if (networkObject == null) { throw new ArgumentNullException(nameof(networkObject), "Cannot spawn null object"); @@ -314,14 +320,6 @@ internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong netwo networkObject.IsSpawned = true; - networkObject.IsSceneObject = sceneObject; - networkObject.NetworkObjectId = networkId; - - networkObject.DestroyWithScene = sceneObject || destroyWithScene; - - networkObject.OwnerClientIdInternal = ownerClientId; - networkObject.IsPlayerObject = playerObject; - SpawnedObjects.Add(networkObject.NetworkObjectId, networkObject); SpawnedObjectsList.Add(networkObject); diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs index 5115083e18..96d11b32cd 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs @@ -84,14 +84,14 @@ private void InitializeTest() // NetworkVariable Value Type Constructor Test Coverage m_NetworkVariableBool = new NetworkVariable(true); - m_NetworkVariableByte = new NetworkVariable(0); + m_NetworkVariableByte = new NetworkVariable((byte)0); m_NetworkVariableColor = new NetworkVariable(new Color(1, 1, 1, 1)); m_NetworkVariableColor32 = new NetworkVariable(new Color32(1, 1, 1, 1)); m_NetworkVariableDouble = new NetworkVariable(1.0); m_NetworkVariableFloat = new NetworkVariable(1.0f); m_NetworkVariableInt = new NetworkVariable(1); m_NetworkVariableLong = new NetworkVariable(1); - m_NetworkVariableSByte = new NetworkVariable(0); + m_NetworkVariableSByte = new NetworkVariable((sbyte)0); m_NetworkVariableQuaternion = new NetworkVariable(Quaternion.identity); m_NetworkVariableShort = new NetworkVariable(256); m_NetworkVariableVector4 = new NetworkVariable(new Vector4(1, 1, 1, 1)); @@ -102,49 +102,45 @@ private void InitializeTest() m_NetworkVariableUInt = new NetworkVariable(1); m_NetworkVariableUShort = new NetworkVariable(1); - - // NetworkVariable NetworkVariableSettings Constructor Test Coverage - var settings = new NetworkVariableSettings(); - settings.ReadPermission = NetworkVariableReadPermission.Everyone; - m_NetworkVariableBool = new NetworkVariable(settings); - m_NetworkVariableByte = new NetworkVariable(settings); - m_NetworkVariableColor = new NetworkVariable(settings); - m_NetworkVariableColor32 = new NetworkVariable(settings); - m_NetworkVariableDouble = new NetworkVariable(settings); - m_NetworkVariableFloat = new NetworkVariable(settings); - m_NetworkVariableInt = new NetworkVariable(settings); - m_NetworkVariableLong = new NetworkVariable(settings); - m_NetworkVariableSByte = new NetworkVariable(settings); - m_NetworkVariableQuaternion = new NetworkVariable(settings); - m_NetworkVariableShort = new NetworkVariable(settings); - m_NetworkVariableVector4 = new NetworkVariable(settings); - m_NetworkVariableVector3 = new NetworkVariable(settings); - m_NetworkVariableVector2 = new NetworkVariable(settings); - m_NetworkVariableRay = new NetworkVariable(settings); - m_NetworkVariableULong = new NetworkVariable(settings); - m_NetworkVariableUInt = new NetworkVariable(settings); - m_NetworkVariableUShort = new NetworkVariable(settings); + m_NetworkVariableBool = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableByte = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableColor = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableColor32 = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableDouble = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableFloat = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableInt = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableLong = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableSByte = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableQuaternion = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableShort = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableVector4 = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableVector3 = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableVector2 = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableRay = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableULong = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableUInt = new NetworkVariable(NetworkVariableReadPermission.Everyone); + m_NetworkVariableUShort = new NetworkVariable(NetworkVariableReadPermission.Everyone); // NetworkVariable Value Type and NetworkVariableSettings Constructor Test Coverage - m_NetworkVariableBool = new NetworkVariable(settings, true); - m_NetworkVariableByte = new NetworkVariable(settings, 0); - m_NetworkVariableColor = new NetworkVariable(settings, new Color(1, 1, 1, 1)); - m_NetworkVariableColor32 = new NetworkVariable(settings, new Color32(1, 1, 1, 1)); - m_NetworkVariableDouble = new NetworkVariable(settings, 1.0); - m_NetworkVariableFloat = new NetworkVariable(settings, 1.0f); - m_NetworkVariableInt = new NetworkVariable(settings, 1); - m_NetworkVariableLong = new NetworkVariable(settings, 1); - m_NetworkVariableSByte = new NetworkVariable(settings, 0); - m_NetworkVariableQuaternion = new NetworkVariable(settings, Quaternion.identity); - m_NetworkVariableShort = new NetworkVariable(settings, 1); - m_NetworkVariableVector4 = new NetworkVariable(settings, new Vector4(1, 1, 1, 1)); - m_NetworkVariableVector3 = new NetworkVariable(settings, new Vector3(1, 1, 1)); - m_NetworkVariableVector2 = new NetworkVariable(settings, new Vector2(1, 1)); - m_NetworkVariableRay = new NetworkVariable(settings, new Ray()); - m_NetworkVariableULong = new NetworkVariable(settings, 1); - m_NetworkVariableUInt = new NetworkVariable(settings, 1); - m_NetworkVariableUShort = new NetworkVariable(settings, 1); + m_NetworkVariableBool = new NetworkVariable(NetworkVariableReadPermission.Everyone, true); + m_NetworkVariableByte = new NetworkVariable(NetworkVariableReadPermission.Everyone, 0); + m_NetworkVariableColor = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Color(1, 1, 1, 1)); + m_NetworkVariableColor32 = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Color32(1, 1, 1, 1)); + m_NetworkVariableDouble = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1.0); + m_NetworkVariableFloat = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1.0f); + m_NetworkVariableInt = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); + m_NetworkVariableLong = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); + m_NetworkVariableSByte = new NetworkVariable(NetworkVariableReadPermission.Everyone, 0); + m_NetworkVariableQuaternion = new NetworkVariable(NetworkVariableReadPermission.Everyone, Quaternion.identity); + m_NetworkVariableShort = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); + m_NetworkVariableVector4 = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Vector4(1, 1, 1, 1)); + m_NetworkVariableVector3 = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Vector3(1, 1, 1)); + m_NetworkVariableVector2 = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Vector2(1, 1)); + m_NetworkVariableRay = new NetworkVariable(NetworkVariableReadPermission.Everyone, new Ray()); + m_NetworkVariableULong = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); + m_NetworkVariableUInt = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); + m_NetworkVariableUShort = new NetworkVariable(NetworkVariableReadPermission.Everyone, 1); // Use this nifty class: NetworkVariableHelper // Tracks if NetworkVariable changed invokes the OnValueChanged callback for the given instance type diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs index 60a5f0e3be..25f9068cf2 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs @@ -22,7 +22,7 @@ public class NetworkVariableTest : NetworkBehaviour public readonly ClientNetworkVariable ClientVar = new ClientNetworkVariable(); public readonly ClientNetworkVariable ClientVarPrivate = - new ClientNetworkVariable(new NetworkVariableSettings { ReadPermission = NetworkVariableReadPermission.OwnerOnly }); + new ClientNetworkVariable(NetworkVariableReadPermission.OwnerOnly); public readonly NetworkVariable TheScalar = new NetworkVariable(); public readonly NetworkList TheList = new NetworkList(); From 764ae721ff6dcc339b2ad8415ab90e62c53636f4 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Thu, 26 Aug 2021 12:49:26 -0700 Subject: [PATCH 5/8] remove ensure initialized --- .../Runtime/Core/NetworkBehaviour.cs | 18 ++++++++++-------- .../Messaging/InternalMessageHandler.cs | 6 +++--- .../Collections/NetworkDictionary.cs | 7 ------- .../NetworkVariable/Collections/NetworkList.cs | 6 ------ .../NetworkVariable/Collections/NetworkSet.cs | 7 ------- .../NetworkVariable/NetworkVariableBase.cs | 8 -------- 6 files changed, 13 insertions(+), 39 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index bb379d50f2..ef4d24462f 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -624,7 +624,7 @@ private bool CouldHaveDirtyNetworkVariables() return false; } - internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, NetworkBehaviour logInstance) + internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -656,7 +656,7 @@ internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, Network { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + NetworkLog.LogWarning($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. => {nameof(NetworkObjectId)}: {NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {NetworkObject.GetNetworkBehaviourOrderIndex(this)} - VariableIndex: {i}"); NetworkLog.LogError($"[{NetworkVariableFields[i].GetType().Name}]"); } @@ -673,7 +673,7 @@ internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, Network // - TwoTen if (NetworkLog.CurrentLogLevel <= LogLevel.Error) { - NetworkLog.LogError($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. No more variables can be read. This is critical. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + NetworkLog.LogError($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. No more variables can be read. This is critical. => {nameof(NetworkObjectId)}: {NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {NetworkObject.GetNetworkBehaviourOrderIndex(this)} - VariableIndex: {i}"); NetworkLog.LogError($"[{NetworkVariableFields[i].GetType().Name}]"); } @@ -684,10 +684,10 @@ internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, Network NetworkVariableFields[i].ReadDelta(stream, NetworkManager.IsServer); NetworkManager.NetworkMetrics.TrackNetworkVariableDeltaReceived( clientId, - logInstance.NetworkObjectId, - logInstance.name, + NetworkObjectId, + name, NetworkVariableFields[i].Name, - logInstance.__getTypeName(), + __getTypeName(), stream.Length); (stream as NetworkBuffer).SkipPadBits(); @@ -698,7 +698,8 @@ internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, Network { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning($"Var delta read too far. {stream.Position - (readStartPos + varSize)} bytes. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + NetworkLog.LogWarning( + $"Var delta read too far. {stream.Position - (readStartPos + varSize)} bytes. => {nameof(NetworkObjectId)}: {NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {NetworkObject.GetNetworkBehaviourOrderIndex(this)} - VariableIndex: {i}"); } stream.Position = readStartPos + varSize; @@ -707,7 +708,8 @@ internal void HandleNetworkVariableDeltas(Stream stream, ulong clientId, Network { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning($"Var delta read too little. {(readStartPos + varSize) - stream.Position} bytes. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); + NetworkLog.LogWarning( + $"Var delta read too little. {(readStartPos + varSize) - stream.Position} bytes. => {nameof(NetworkObjectId)}: {NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {NetworkObject.GetNetworkBehaviourOrderIndex(this)} - VariableIndex: {i}"); } stream.Position = readStartPos + varSize; diff --git a/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs b/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs index fd4249c65c..cd89b1f8e7 100644 --- a/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs +++ b/com.unity.netcode.gameobjects/Runtime/Messaging/InternalMessageHandler.cs @@ -211,9 +211,9 @@ public void HandleNetworkVariableDelta(ulong clientId, Stream stream) if (NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(networkObjectId, out NetworkObject networkObject)) { - NetworkBehaviour instance = networkObject.GetNetworkBehaviourAtOrderIndex(networkBehaviourIndex); + NetworkBehaviour behaviour = networkObject.GetNetworkBehaviourAtOrderIndex(networkBehaviourIndex); - if (instance == null) + if (behaviour == null) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { @@ -222,7 +222,7 @@ public void HandleNetworkVariableDelta(ulong clientId, Stream stream) } else { - instance.HandleNetworkVariableDeltas(stream, clientId, instance); + behaviour.HandleNetworkVariableDeltas(stream, clientId); } } else if (NetworkManager.IsServer) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 6adde145b5..43d224ffc9 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -303,8 +303,6 @@ public TValue this[TKey key] get => m_Dictionary[key]; set { - EnsureInitialized(); - m_Dictionary[key] = value; var dictionaryEvent = new NetworkDictionaryEvent() @@ -334,7 +332,6 @@ public TValue this[TKey key] /// public void Add(TKey key, TValue value) { - EnsureInitialized(); m_Dictionary.Add(key, value); var dictionaryEvent = new NetworkDictionaryEvent() @@ -350,7 +347,6 @@ public void Add(TKey key, TValue value) /// public void Add(KeyValuePair item) { - EnsureInitialized(); m_Dictionary.Add(item); var dictionaryEvent = new NetworkDictionaryEvent() @@ -366,7 +362,6 @@ public void Add(KeyValuePair item) /// public void Clear() { - EnsureInitialized(); m_Dictionary.Clear(); var dictionaryEvent = new NetworkDictionaryEvent() @@ -404,7 +399,6 @@ public IEnumerator> GetEnumerator() /// public bool Remove(TKey key) { - EnsureInitialized(); m_Dictionary.Remove(key); TValue value; @@ -426,7 +420,6 @@ public bool Remove(TKey key) /// public bool Remove(KeyValuePair item) { - EnsureInitialized(); m_Dictionary.Remove(item); var dictionaryEvent = new NetworkDictionaryEvent() diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index 74acdabf05..67d2207901 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -332,7 +332,6 @@ IEnumerator IEnumerable.GetEnumerator() /// public void Add(T item) { - EnsureInitialized(); m_List.Add(item); var listEvent = new NetworkListEvent() @@ -348,7 +347,6 @@ public void Add(T item) /// public void Clear() { - EnsureInitialized(); m_List.Clear(); var listEvent = new NetworkListEvent() @@ -374,7 +372,6 @@ public void CopyTo(T[] array, int arrayIndex) /// public bool Remove(T item) { - EnsureInitialized(); m_List.Remove(item); var listEvent = new NetworkListEvent() @@ -402,7 +399,6 @@ public int IndexOf(T item) /// public void Insert(int index, T item) { - EnsureInitialized(); m_List.Insert(index, item); var listEvent = new NetworkListEvent() @@ -418,7 +414,6 @@ public void Insert(int index, T item) /// public void RemoveAt(int index) { - EnsureInitialized(); m_List.RemoveAt(index); var listEvent = new NetworkListEvent() @@ -437,7 +432,6 @@ public T this[int index] get => m_List[index]; set { - EnsureInitialized(); m_List[index] = value; var listEvent = new NetworkListEvent() diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index b689a19238..58ba209494 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -293,8 +293,6 @@ public bool SetEquals(IEnumerable other) /// public void SymmetricExceptWith(IEnumerable other) { - EnsureInitialized(); - foreach (T value in other) { if (m_Set.Contains(value)) @@ -323,8 +321,6 @@ public void SymmetricExceptWith(IEnumerable other) /// public void UnionWith(IEnumerable other) { - EnsureInitialized(); - foreach (T value in other) { if (!m_Set.Contains(value)) @@ -348,7 +344,6 @@ public void UnionWith(IEnumerable other) public bool Add(T item) { - EnsureInitialized(); m_Set.Add(item); var setEvent = new NetworkSetEvent() @@ -372,7 +367,6 @@ public bool Add(T item) /// public void Clear() { - EnsureInitialized(); m_Set.Clear(); var setEvent = new NetworkSetEvent() @@ -402,7 +396,6 @@ public void CopyTo(T[] array, int arrayIndex) /// public bool Remove(T item) { - EnsureInitialized(); m_Set.Remove(item); var setEvent = new NetworkSetEvent() diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs index d80f51a1b1..e11a8ece2e 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs @@ -25,14 +25,6 @@ protected NetworkVariableBase(NetworkVariableReadPermission readPermIn = Network ReadPerm = readPermIn; } - private protected void EnsureInitialized() - { - if (!m_NetworkBehaviour) - { - throw new InvalidOperationException("Cannot access NetworkVariable before it's initialized"); - } - } - private protected bool m_IsDirty; /// From 0e84dd3d40eb2dff460f5087073b3795e7975c2e Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Thu, 26 Aug 2021 13:17:59 -0700 Subject: [PATCH 6/8] moved init, removed unused var --- .../Runtime/Core/NetworkObject.cs | 4 ++-- .../Runtime/Spawning/NetworkSpawnManager.cs | 23 +++++++++++++------ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs index 53d16f0b9a..134582b259 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs @@ -241,7 +241,7 @@ public void NetworkShow(ulong clientId) Observers.Add(clientId); - NetworkManager.SpawnManager.SendSpawnCallForObject(clientId, OwnerClientId, this); + NetworkManager.SpawnManager.SendSpawnCallForObject(clientId, this); } /// @@ -499,7 +499,7 @@ private void SpawnInternal(bool destroyWithScene, ulong? ownerClientId, bool pla { if (Observers.Contains(NetworkManager.ConnectedClientsList[i].ClientId)) { - NetworkManager.SpawnManager.SendSpawnCallForObject(NetworkManager.ConnectedClientsList[i].ClientId, ownerId, this); + NetworkManager.SpawnManager.SendSpawnCallForObject(NetworkManager.ConnectedClientsList[i].ClientId, this); } } } diff --git a/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs b/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs index 28d7d6b342..7402a5bd07 100644 --- a/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs +++ b/com.unity.netcode.gameobjects/Runtime/Spawning/NetworkSpawnManager.cs @@ -291,12 +291,6 @@ internal NetworkObject CreateLocalNetworkObject(bool isSceneObject, uint globalO // Ran on both server and client internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong? ownerClientId, Stream dataStream, bool readNetworkVariable, bool destroyWithScene) { - networkObject.IsSceneObject = sceneObject; - networkObject.NetworkObjectId = networkId; - networkObject.DestroyWithScene = sceneObject || destroyWithScene; - networkObject.OwnerClientIdInternal = ownerClientId; - networkObject.IsPlayerObject = playerObject; - if (networkObject == null) { throw new ArgumentNullException(nameof(networkObject), "Cannot spawn null object"); @@ -318,8 +312,23 @@ internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong netwo return; } + // this initialization really should be at the bottom of the function networkObject.IsSpawned = true; + // this initialization really should be at the top of this function. If and when we break the + // NetworkVariable dependency on NetworkBehaviour, this otherwise creates problems because + // SetNetworkVariableData above calls InitializeVariables, and the 'baked out' data isn't ready there; + // the current design banks on getting the network behaviour set and then only reading from it + // after the below initialization code. However cowardice compels me to hold off on moving this until + // that commit + networkObject.IsSceneObject = sceneObject; + networkObject.NetworkObjectId = networkId; + + networkObject.DestroyWithScene = sceneObject || destroyWithScene; + + networkObject.OwnerClientIdInternal = ownerClientId; + networkObject.IsPlayerObject = playerObject; + SpawnedObjects.Add(networkObject.NetworkObjectId, networkObject); SpawnedObjectsList.Add(networkObject); @@ -361,7 +370,7 @@ internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong netwo networkObject.InvokeBehaviourNetworkSpawn(); } - internal void SendSpawnCallForObject(ulong clientId, ulong ownerClientId, NetworkObject networkObject) + internal void SendSpawnCallForObject(ulong clientId, NetworkObject networkObject) { if (!NetworkManager.NetworkConfig.UseSnapshotSpawn) { From 08f38f69d37561321ead2184a899374f89f7e38e Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Thu, 26 Aug 2021 14:31:09 -0700 Subject: [PATCH 7/8] whitespace / include fixes --- .../Runtime/Metrics/NetworkObjectProvider.cs | 2 +- .../NetworkVariable/Collections/NetworkDictionary.cs | 5 ++--- .../Runtime/NetworkVariable/Collections/NetworkList.cs | 1 - .../Runtime/NetworkVariable/Collections/NetworkSet.cs | 3 +-- .../Runtime/NetworkVariable/NetworkVariable.cs | 8 ++++++-- .../Runtime/NetworkVariable/NetworkVariableBase.cs | 2 -- .../Tests/Runtime/Profiling/NetworkVariableNameTests.cs | 2 +- 7 files changed, 11 insertions(+), 12 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/Metrics/NetworkObjectProvider.cs b/com.unity.netcode.gameobjects/Runtime/Metrics/NetworkObjectProvider.cs index 7bda94e6cf..e1f6f011b3 100644 --- a/com.unity.netcode.gameobjects/Runtime/Metrics/NetworkObjectProvider.cs +++ b/com.unity.netcode.gameobjects/Runtime/Metrics/NetworkObjectProvider.cs @@ -1,4 +1,4 @@ -#if MULTIPLAYER_TOOLS +#if MULTIPLAYER_TOOLS using Unity.Multiplayer.Tools; using UnityEngine; diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 43d224ffc9..2f19823a20 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -1,4 +1,3 @@ -using System; using System.Collections; using System.Collections.Generic; using System.IO; @@ -441,8 +440,8 @@ IEnumerator IEnumerable.GetEnumerator() private void HandleAddDictionaryEvent(NetworkDictionaryEvent dictionaryEvent) { - m_DirtyEvents.Add(dictionaryEvent); - OnDictionaryChanged?.Invoke(dictionaryEvent); + m_DirtyEvents.Add(dictionaryEvent); + OnDictionaryChanged?.Invoke(dictionaryEvent); } public int LastModifiedTick diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index 67d2207901..c288c6389f 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -1,4 +1,3 @@ -using System; using System.Collections; using System.Collections.Generic; using System.IO; diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index 58ba209494..b80edc4dfa 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -1,5 +1,4 @@ #if !NET35 -using System; using System.Collections; using System.Collections.Generic; using System.IO; @@ -10,7 +9,7 @@ namespace Unity.Netcode /// Event based NetworkVariable container for syncing Sets /// /// The type for the set - public class NetworkSet : NetworkVariableBase, ISet where T: unmanaged + public class NetworkSet : NetworkVariableBase, ISet where T : unmanaged { private readonly ISet m_Set = new HashSet(); private readonly List> m_DirtyEvents = new List>(); diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index ebf3ed450f..34810cef4a 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -26,13 +26,17 @@ public class NetworkVariable : NetworkVariableBase where T : unmanaged /// Creates a NetworkVariable with the default value and custom read permission /// /// The read permission for the NetworkVariable - public NetworkVariable() {} + public NetworkVariable() + { + } /// /// Creates a NetworkVariable with the default value and custom read permission /// /// The read permission for the NetworkVariable - public NetworkVariable(NetworkVariableReadPermission readPerm) : base(readPerm) {} + public NetworkVariable(NetworkVariableReadPermission readPerm) : base(readPerm) + { + } /// /// Creates a NetworkVariable with a custom value and custom settings diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs index e11a8ece2e..16f0257dc7 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs @@ -1,6 +1,4 @@ -using System; using System.IO; -using UnityEditor.SceneManagement; namespace Unity.Netcode { diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Profiling/NetworkVariableNameTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Profiling/NetworkVariableNameTests.cs index 5adbc4ffbf..4161372187 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Profiling/NetworkVariableNameTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Profiling/NetworkVariableNameTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using NUnit.Framework; namespace Unity.Netcode.RuntimeTests From f0eb64cb2bec004d357e55f0539bfaa91c770c0d Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Thu, 26 Aug 2021 15:36:48 -0700 Subject: [PATCH 8/8] remove unnecessary requires --- .../Runtime/NetworkVariable/NetworkVariableBase.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs index e11a8ece2e..16f0257dc7 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs @@ -1,6 +1,4 @@ -using System; using System.IO; -using UnityEditor.SceneManagement; namespace Unity.Netcode {