Skip to content

Commit c674117

Browse files
fix: NetworkList changes pending during client synchronization are applied twice (#4215)
* fix: NetworkList changes pending during client synchronization are applied twice Override WriteFieldSynchronization in NetworkList<T> so a client synchronized while local changes are still pending receives the list as of the last sent delta, mirroring NetworkVariable<T>. The pending events are then applied exactly once with the next delta. Fixes #4179 * Update CHANGELOG * fix: keep NetworkObject queued when NetworkShow cannot flush throttled updates ForceSendIfDirtyOnNetworkShow removed the NetworkObject from the updater even when NetworkVariableUpdateTraits held back its dirty variables, so those changes were not sent until the variable was modified again. Re-queue the object when anything is still dirty after the forced flush, and add a regression test for showing an object while NetworkList updates are throttled. --------- Co-authored-by: Shubham Kumar <146586770+quantum-shubham@users.noreply.github.com>
1 parent 924d4c5 commit c674117

4 files changed

Lines changed: 151 additions & 3 deletions

File tree

‎com.unity.netcode.gameobjects/CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ Additional documentation and release notes are available at [Multiplayer Documen
2222

2323
### Fixed
2424

25+
- Issue where a client synchronized while a `NetworkList<T>` still had unsent changes applied those changes twice, resulting in duplicate entries and index-based events landing on the wrong elements on that client. (#4215)
26+
- Issue where showing a `NetworkObject` with `NetworkShow` while its `NetworkVariable` updates were held back by `NetworkVariableUpdateTraits` stopped those pending changes from being sent until the variable was modified again. (#4215)
2527
- Issue where moving a `NetworkObject` into another scene made the clients that did not observe it log "Trying to synchronize NetworkObjectId but it was not spawned". The scene migration is now only sent to the clients that observe the `NetworkObject`. (#4185)
2628
- Issue where a `NetworkObject` that was moved into another scene while hidden from a client spawned in that client's active scene when it was shown with `NetworkShow`, instead of the scene it is in on the server. (#4185)
2729
- Issue where mixed authority nested `NetworkTransform` instances could stop child/nested instances from updating because an authoritative `NetworkTransform` (root or otherwise) would remove the `NetworkObject` from the update group, preventing non-authoritative instances from updating their state on the authority side. (#4169)

‎com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviourUpdater.cs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,19 @@ internal void ForceSendIfDirtyOnNetworkShow(NetworkObject networkObject)
138138
// Remove it from the pending and queued dirty objects lists
139139
m_PendingDirtyNetworkObjects.Remove(networkObject);
140140
m_DirtyNetworkObjects.Remove(networkObject);
141+
142+
// Anything still dirty was held back by its update traits, keep it queued so a later tick sends it
143+
foreach (var behaviour in networkObject.ChildNetworkBehaviours.Values)
144+
{
145+
foreach (var networkVariable in behaviour.NetworkVariableFields)
146+
{
147+
if (networkVariable.IsDirty())
148+
{
149+
AddForUpdate(networkObject);
150+
return;
151+
}
152+
}
153+
}
141154
}
142155

143156
/// <summary>

‎com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs‎

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ public class NetworkList<T> : NetworkVariableBase where T : unmanaged, IEquatabl
1616
private NativeList<T> m_List = new NativeList<T>(64, Allocator.Persistent);
1717
private NativeList<NetworkListEvent<T>> m_DirtyEvents = new NativeList<NetworkListEvent<T>>(64, Allocator.Persistent);
1818

19+
// The list as it was before the first local change that is still pending in m_DirtyEvents
20+
private NativeList<T> m_LastSentList = new NativeList<T>(64, Allocator.Persistent);
21+
private bool m_HasLastSentList;
22+
1923
/// <summary>
2024
/// Delegate type for list changed event
2125
/// </summary>
@@ -67,6 +71,7 @@ public override void ResetDirty()
6771
{
6872
m_DirtyEvents.Clear();
6973
}
74+
m_HasLastSentList = false;
7075
}
7176

7277
/// <inheritdoc cref="NetworkVariable{T}.IsDirty"/>
@@ -149,10 +154,42 @@ private T ReadValue(FastBufferReader reader)
149154
/// <inheritdoc cref="NetworkVariable{T}.WriteField"/>
150155
public override void WriteField(FastBufferWriter writer)
151156
{
152-
writer.WriteValueSafe((ushort)m_List.Length);
153-
for (int i = 0; i < m_List.Length; i++)
157+
WriteList(writer, m_List);
158+
}
159+
160+
internal override void WriteFieldSynchronization(FastBufferWriter writer)
161+
{
162+
// The pending events are sent to the synchronizing client with the next delta, so it must
163+
// receive the list they apply to. Otherwise it would apply them twice.
164+
if (m_HasLastSentList && m_DirtyEvents.Length > 0)
165+
{
166+
WriteList(writer, m_LastSentList);
167+
}
168+
else
169+
{
170+
base.WriteFieldSynchronization(writer);
171+
}
172+
}
173+
174+
private static void WriteList(FastBufferWriter writer, NativeList<T> list)
175+
{
176+
writer.WriteValueSafe((ushort)list.Length);
177+
for (int i = 0; i < list.Length; i++)
154178
{
155-
NetworkVariableSerialization<T>.Serializer.Write(writer, ref m_List.ElementAt(i));
179+
NetworkVariableSerialization<T>.Serializer.Write(writer, ref list.ElementAt(i));
180+
}
181+
}
182+
183+
/// <summary>
184+
/// Invoked before a local change. Keeps a copy of the list as of the last sent delta
185+
/// so <see cref="WriteFieldSynchronization"/> can send it while changes are pending.
186+
/// </summary>
187+
private void CaptureLastSentList()
188+
{
189+
if (m_DirtyEvents.Length == 0)
190+
{
191+
m_LastSentList.CopyFrom(m_List);
192+
m_HasLastSentList = true;
156193
}
157194
}
158195

@@ -439,6 +476,7 @@ public void Add(T item)
439476
return;
440477
}
441478

479+
CaptureLastSentList();
442480
m_List.Add(item);
443481

444482
var listEvent = new NetworkListEvent<T>()
@@ -466,6 +504,7 @@ public void Clear()
466504
return;
467505
}
468506

507+
CaptureLastSentList();
469508
m_List.Clear();
470509

471510
var listEvent = new NetworkListEvent<T>()
@@ -510,6 +549,7 @@ public bool Remove(T item)
510549
return false;
511550
}
512551

552+
CaptureLastSentList();
513553
m_List.RemoveAt(index);
514554
var listEvent = new NetworkListEvent<T>()
515555
{
@@ -553,6 +593,7 @@ public void Insert(int index, T item)
553593
return;
554594
}
555595

596+
CaptureLastSentList();
556597
if (index < m_List.Length)
557598
{
558599
m_List.InsertRangeWithBeginEnd(index, index + 1);
@@ -589,6 +630,7 @@ public void RemoveAt(int index)
589630
}
590631

591632
var value = m_List[index];
633+
CaptureLastSentList();
592634
m_List.RemoveAt(index);
593635

594636
var listEvent = new NetworkListEvent<T>()
@@ -631,6 +673,7 @@ public void Set(int index, T value, bool forceUpdate = false)
631673
return;
632674
}
633675

676+
CaptureLastSentList();
634677
m_List[index] = value;
635678

636679
var listEvent = new NetworkListEvent<T>()
@@ -706,6 +749,11 @@ public override void Dispose()
706749
m_DirtyEvents.Dispose();
707750
}
708751

752+
if (m_LastSentList.IsCreated)
753+
{
754+
m_LastSentList.Dispose();
755+
}
756+
709757
base.Dispose();
710758
}
711759
}

‎com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariable/NetworkListTests.cs‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,91 @@ private bool OnVerifyData(StringBuilder errorLog)
8080
return true;
8181
}
8282

83+
/// <summary>
84+
/// Validates that a client synchronized while the list still has unsent changes
85+
/// does not apply those changes twice (snapshot + next delta).
86+
/// </summary>
87+
[UnityTest]
88+
public IEnumerator LateJoinWithPendingChanges()
89+
{
90+
var authority = GetAuthorityNetworkManager();
91+
var instantiatedObject = SpawnObject(m_ListObjectPrefab, authority).GetComponent<NetworkObject>();
92+
m_TestObjectId = instantiatedObject.NetworkObjectId;
93+
94+
yield return WaitForSpawnedOnAllOrTimeOut(instantiatedObject);
95+
AssertOnTimeout("[Setup] Failed to spawn list object");
96+
97+
var list = instantiatedObject.GetComponent<NetworkListTest>().TheList;
98+
m_ExpectedValues.Clear();
99+
for (int i = 0; i < 5; i++)
100+
{
101+
m_ExpectedValues.Add(i);
102+
list.Add(i);
103+
}
104+
105+
yield return WaitForConditionOrTimeOut(OnVerifyData);
106+
AssertOnTimeout("[Setup] Failed to add items to list");
107+
108+
// Hold back deltas so these changes are still pending when the new client synchronizes
109+
list.SetUpdateTraits(new NetworkVariableUpdateTraits { MinSecondsBetweenUpdates = 3600 });
110+
list.Add(100);
111+
m_ExpectedValues.Add(100);
112+
list.Insert(0, 101);
113+
m_ExpectedValues.Insert(0, 101);
114+
list.RemoveAt(2);
115+
m_ExpectedValues.RemoveAt(2);
116+
list[1] = 102;
117+
m_ExpectedValues[1] = 102;
118+
list.Remove(3);
119+
m_ExpectedValues.Remove(3);
120+
121+
yield return CreateAndStartNewClient();
122+
Assert.IsTrue(list.IsDirty(), "[Setup] Changes should still be pending after the new client synchronized");
123+
124+
list.SetUpdateTraits(default);
125+
yield return WaitForConditionOrTimeOut(OnVerifyData);
126+
AssertOnTimeout("Late joined client did not match the authority's list");
127+
}
128+
129+
/// <summary>
130+
/// Validates that showing an object while list updates are held back by update traits
131+
/// still delivers the pending changes once they can be sent.
132+
/// </summary>
133+
[UnityTest]
134+
public IEnumerator NetworkShowWithThrottledPendingChanges()
135+
{
136+
var authority = GetAuthorityNetworkManager();
137+
var nonAuthority = GetNonAuthorityNetworkManager();
138+
var instantiatedObject = SpawnObject(m_ListObjectPrefab, authority).GetComponent<NetworkObject>();
139+
m_TestObjectId = instantiatedObject.NetworkObjectId;
140+
141+
yield return WaitForSpawnedOnAllOrTimeOut(instantiatedObject);
142+
AssertOnTimeout("[Setup] Failed to spawn list object");
143+
144+
instantiatedObject.NetworkHide(nonAuthority.LocalClientId);
145+
yield return WaitForConditionOrTimeOut(() => !nonAuthority.SpawnManager.SpawnedObjects.ContainsKey(m_TestObjectId));
146+
AssertOnTimeout("[Setup] Failed to hide list object");
147+
148+
// Hold back deltas so these changes are still pending when the object is shown
149+
var list = instantiatedObject.GetComponent<NetworkListTest>().TheList;
150+
list.SetUpdateTraits(new NetworkVariableUpdateTraits { MinSecondsBetweenUpdates = 3600 });
151+
m_ExpectedValues.Clear();
152+
for (int i = 0; i < 5; i++)
153+
{
154+
m_ExpectedValues.Add(i);
155+
list.Add(i);
156+
}
157+
158+
instantiatedObject.NetworkShow(nonAuthority.LocalClientId);
159+
yield return WaitForConditionOrTimeOut(() => nonAuthority.SpawnManager.SpawnedObjects.ContainsKey(m_TestObjectId));
160+
AssertOnTimeout("[Setup] Failed to show list object");
161+
Assert.IsTrue(list.IsDirty(), "[Setup] Changes should still be pending after the object was shown");
162+
163+
list.SetUpdateTraits(default);
164+
yield return WaitForConditionOrTimeOut(OnVerifyData);
165+
AssertOnTimeout("Clients did not receive the changes that were pending when the object was shown");
166+
}
167+
83168
[UnityTest]
84169
public IEnumerator ValidateNetworkListSynchronization()
85170
{

0 commit comments

Comments
 (0)