Skip to content

Commit

Permalink
fix(SyncDictionary): Clear after Callback (#3789)
Browse files Browse the repository at this point in the history
  • Loading branch information
MrGadget1024 committed Mar 22, 2024
1 parent f7329f6 commit 74a4f25
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
8 changes: 6 additions & 2 deletions Assets/Mirror/Core/SyncDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,12 +195,14 @@ public override void OnDeserializeDelta(NetworkReader reader)
case Operation.OP_CLEAR:
if (apply)
{
objects.Clear();
// add dirty + changes.
// ClientToServer needs to set dirty in server OnDeserialize.
// no access check: server OnDeserialize can always
// write, even for ClientToServer (for broadcasting).
AddOperation(Operation.OP_CLEAR, default, default, false);
// clear after invoking the callback so users can iterate the dictionary
// and take appropriate action on the items before they are wiped.
objects.Clear();
}
break;

Expand Down Expand Up @@ -231,8 +233,10 @@ public override void OnDeserializeDelta(NetworkReader reader)

public void Clear()
{
objects.Clear();
AddOperation(Operation.OP_CLEAR, default, default, true);
// clear after invoking the callback so users can iterate the dictionary
// and take appropriate action on the items before they are wiped.
objects.Clear();
}

public bool ContainsKey(TKey key) => objects.ContainsKey(key);
Expand Down
10 changes: 10 additions & 0 deletions Assets/Mirror/Tests/Editor/SyncCollections/SyncDictionaryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,19 @@ public void TestAdd()
[Test]
public void TestClear()
{
// Verifies that the clear method works and that the data is still present for the Callback.
bool called = false;
clientSyncDictionary.Callback = (op, index, item) =>
{
called = true;
Assert.That(op, Is.EqualTo(SyncDictionary<int, string>.Operation.OP_CLEAR));
Assert.That(clientSyncDictionary.Count, Is.EqualTo(3));
};
serverSyncDictionary.Clear();
SerializeDeltaTo(serverSyncDictionary, clientSyncDictionary);
Assert.That(serverSyncDictionary, Is.EquivalentTo(new SyncDictionary<int, string>()));
Assert.That(called, Is.True);
}

[Test]
Expand Down

0 comments on commit 74a4f25

Please sign in to comment.