Skip to content

Commit 7d4e850

Browse files
fix: [Backport] MTTB-1273 Inconsistent scene name in scene event (#3487)
<!-- Replace this block with what this PR does and why. Describe what you'd like reviewers to know, how you applied the engineering principles, and any interesting tradeoffs made. Delete bullet points below that don't apply, and update the changelog section as appropriate. --> <!-- Add short version of the JIRA ticket to the PR title (e.g. "feat: new shiny feature [MTT-123]") --> [MTTB-1278](https://jira.unity3d.com/browse/MTTB-1273) fixes: #3418 ## Changelog - Added: A `ScenePath` field on the `SceneEvent` returned by the `OnSceneEvent` callback. - Fixed: Various bugs around the `OnSceneEvent` callback. ## Testing and Documentation - Includes unit tests. <!-- Uncomment and mark items off with a * if this PR deprecates any API: ### Deprecated API - [ ] An `[Obsolete]` attribute was added along with a `(RemovedAfter yyyy-mm-dd)` entry. - [ ] An [api updater] was added. - [ ] Deprecation of the API is explained in the CHANGELOG. - [ ] The users can understand why this API was removed and what they should use instead. --> ## Backport <!-- If this is a backport: - Add the following to the PR title: "\[Backport\] ..." . - Link to the original PR. If this needs a backport - state this here If a backport is not needed please provide the reason why. If the "Backports" section is not present it will lead to a CI test failure. --> This is a backport of #3458 --------- Co-authored-by: Noel Stephens <[email protected]>
1 parent c065fec commit 7d4e850

File tree

7 files changed

+653
-147
lines changed

7 files changed

+653
-147
lines changed

com.unity.netcode.gameobjects/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
1515

1616
### Fixed
1717

18+
- Fixed inconsistencies in the `OnSceneEvent` callback. (#3487)
1819
- Fixed issue where `NetworkClient` could persist some settings if re-using the same `NetworkManager` instance. (#3494)
1920
- Fixed issue where a pooled `NetworkObject` was not resetting the internal latest parent property when despawned. (#3494)
2021
- Fixed issue where the initial client synchronization pre-serialization process was not excluding spawned `NetworkObjects` that already had pending visibility for the client being synchronized. (#3493)

com.unity.netcode.gameobjects/Runtime/SceneManagement/NetworkSceneManager.cs

Lines changed: 87 additions & 146 deletions
Large diffs are not rendered by default.

com.unity.netcode.gameobjects/TestHelpers/Runtime/NetcodeIntegrationTest.cs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Linq;
55
using System.Reflection;
66
using System.Runtime.CompilerServices;
7+
using System.Text;
78
using NUnit.Framework;
89
using Unity.Netcode.RuntimeTests;
910
using Unity.Netcode.Transports.UTP;
@@ -36,6 +37,8 @@ public abstract class NetcodeIntegrationTest
3637
/// </summary>
3738
protected static WaitForSecondsRealtime s_DefaultWaitForTick = new WaitForSecondsRealtime(1.0f / k_DefaultTickRate);
3839

40+
private readonly StringBuilder m_InternalErrorLog = new StringBuilder();
41+
3942
/// <summary>
4043
/// An instance of <see cref="NetcodeLogAssert"/> used to capture and assert log messages during integration tests.
4144
/// This helps in verifying that expected log messages are produced and unexpected log messages are not.
@@ -1466,6 +1469,27 @@ public bool WaitForConditionOrTimeOutWithTimeTravel(IConditionalPredicate condit
14661469
return success;
14671470
}
14681471

1472+
/// <summary>
1473+
/// Waits until the specified condition returns true or a timeout occurs, then asserts if the timeout was reached.
1474+
/// This overload allows the condition to provide additional error details via a <see cref="StringBuilder"/>.
1475+
/// </summary>
1476+
/// <param name="checkForCondition">A delegate that takes a <see cref="StringBuilder"/> for error details and returns true when the desired condition is met.</param>
1477+
/// <param name="timeOutHelper">An optional <see cref="TimeoutHelper"/> to control the timeout period. If null, the default timeout is used.</param>
1478+
/// <returns>An <see cref="IEnumerator"/> for use in Unity coroutines.</returns>
1479+
protected IEnumerator WaitForConditionOrTimeOut(Func<StringBuilder, bool> checkForCondition, TimeoutHelper timeOutHelper = null)
1480+
{
1481+
if (checkForCondition == null)
1482+
{
1483+
throw new ArgumentNullException($"checkForCondition cannot be null!");
1484+
}
1485+
1486+
yield return WaitForConditionOrTimeOut(() =>
1487+
{
1488+
m_InternalErrorLog.Clear();
1489+
return checkForCondition(m_InternalErrorLog);
1490+
}, timeOutHelper);
1491+
}
1492+
14691493
/// <summary>
14701494
/// Validation for clients connected.
14711495
/// </summary>
@@ -1736,6 +1760,13 @@ public NetcodeIntegrationTest(HostOrServer hostOrServer)
17361760
protected void AssertOnTimeout(string timeOutErrorMessage, TimeoutHelper assignedTimeoutHelper = null)
17371761
{
17381762
var timeoutHelper = assignedTimeoutHelper ?? s_GlobalTimeoutHelper;
1763+
if (m_InternalErrorLog.Length > 0)
1764+
{
1765+
Assert.False(timeoutHelper.TimedOut, $"{timeOutErrorMessage}\n{m_InternalErrorLog}");
1766+
m_InternalErrorLog.Clear();
1767+
return;
1768+
}
1769+
17391770
Assert.False(timeoutHelper.TimedOut, timeOutErrorMessage);
17401771
}
17411772

@@ -1757,7 +1788,7 @@ private void UnloadRemainingScenes()
17571788
}
17581789
}
17591790

1760-
private System.Text.StringBuilder m_WaitForLog = new System.Text.StringBuilder();
1791+
private StringBuilder m_WaitForLog = new StringBuilder();
17611792

17621793
private void LogWaitForMessages()
17631794
{
Lines changed: 281 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,281 @@
1+
using System.Collections;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using NUnit.Framework;
6+
using Unity.Netcode;
7+
using Unity.Netcode.TestHelpers.Runtime;
8+
using UnityEngine.SceneManagement;
9+
using UnityEngine.TestTools;
10+
11+
namespace TestProject.RuntimeTests
12+
{
13+
[TestFixture(HostOrServer.Host)]
14+
[TestFixture(HostOrServer.Server)]
15+
public class OnSceneEventCallbackTests : NetcodeIntegrationTest
16+
{
17+
protected override int NumberOfClients => 1;
18+
19+
private const string k_SceneToLoad = "EmptyScene";
20+
private const string k_PathToLoad = "Assets/Scenes/EmptyScene.unity";
21+
22+
public OnSceneEventCallbackTests(HostOrServer hostOrServer) : base(hostOrServer)
23+
{
24+
}
25+
26+
private struct ExpectedEvent
27+
{
28+
public SceneEvent SceneEvent;
29+
public string SceneName;
30+
public string ScenePath;
31+
}
32+
33+
private readonly Queue<ExpectedEvent> m_ExpectedEventQueue = new();
34+
35+
private static int s_NumEventsProcessed;
36+
private void OnSceneEvent(SceneEvent sceneEvent)
37+
{
38+
VerboseDebug($"OnSceneEvent! Type: {sceneEvent.SceneEventType}. for client: {sceneEvent.ClientId}");
39+
if (m_ExpectedEventQueue.Count > 0)
40+
{
41+
var expectedEvent = m_ExpectedEventQueue.Dequeue();
42+
43+
ValidateEventsAreEqual(expectedEvent.SceneEvent, sceneEvent);
44+
45+
// Only LoadComplete events have an attached scene
46+
if (sceneEvent.SceneEventType == SceneEventType.LoadComplete)
47+
{
48+
ValidateReceivedScene(expectedEvent, sceneEvent.Scene);
49+
}
50+
}
51+
else
52+
{
53+
Assert.Fail($"Received unexpected event at index {s_NumEventsProcessed}: {sceneEvent.SceneEventType}");
54+
}
55+
s_NumEventsProcessed++;
56+
}
57+
58+
public enum ClientType
59+
{
60+
Authority,
61+
NonAuthority,
62+
}
63+
64+
public enum Action
65+
{
66+
Load,
67+
Unload,
68+
}
69+
70+
[UnityTest]
71+
public IEnumerator LoadAndUnloadCallbacks([Values] ClientType clientType, [Values] Action action)
72+
{
73+
yield return RunSceneEventCallbackTest(clientType, action, k_SceneToLoad);
74+
}
75+
76+
[UnityTest]
77+
public IEnumerator LoadSceneFromPath([Values] ClientType clientType)
78+
{
79+
yield return RunSceneEventCallbackTest(clientType, Action.Load, k_PathToLoad);
80+
}
81+
82+
private IEnumerator RunSceneEventCallbackTest(ClientType clientType, Action action, string loadCall)
83+
{
84+
m_EnableVerboseDebug = true;
85+
var client = m_ClientNetworkManagers[0];
86+
var managerToTest = clientType == ClientType.Authority ? m_ServerNetworkManager : client;
87+
88+
89+
var expectedCompletedClients = new List<ulong> { client.LocalClientId };
90+
// the authority ID is not inside ClientsThatCompleted when running as a server
91+
if (m_UseHost)
92+
{
93+
expectedCompletedClients.Insert(0, m_ServerNetworkManager.LocalClientId);
94+
}
95+
96+
Scene loadedScene = default;
97+
if (action == Action.Unload)
98+
{
99+
// Load the scene initially
100+
m_ServerNetworkManager.SceneManager.LoadScene(k_SceneToLoad, LoadSceneMode.Additive);
101+
102+
yield return WaitForConditionOrTimeOut(ValidateSceneIsLoaded);
103+
AssertOnTimeout($"[Setup] Timed out waiting for client to load the scene {k_SceneToLoad}!");
104+
105+
// Wait for any pending messages to be processed
106+
yield return s_DefaultWaitForTick;
107+
108+
// Get a reference to the scene to test
109+
loadedScene = SceneManager.GetSceneByName(k_SceneToLoad);
110+
}
111+
112+
s_NumEventsProcessed = 0;
113+
m_ExpectedEventQueue.Clear();
114+
m_ExpectedEventQueue.Enqueue(new ExpectedEvent()
115+
{
116+
SceneEvent = new SceneEvent()
117+
{
118+
SceneEventType = action == Action.Load ? SceneEventType.Load : SceneEventType.Unload,
119+
LoadSceneMode = LoadSceneMode.Additive,
120+
SceneName = k_SceneToLoad,
121+
ScenePath = k_PathToLoad,
122+
ClientId = managerToTest.LocalClientId,
123+
},
124+
});
125+
m_ExpectedEventQueue.Enqueue(new ExpectedEvent()
126+
{
127+
SceneEvent = new SceneEvent()
128+
{
129+
SceneEventType = action == Action.Load ? SceneEventType.LoadComplete : SceneEventType.UnloadComplete,
130+
LoadSceneMode = LoadSceneMode.Additive,
131+
SceneName = k_SceneToLoad,
132+
ScenePath = k_PathToLoad,
133+
ClientId = managerToTest.LocalClientId,
134+
},
135+
SceneName = action == Action.Load ? k_SceneToLoad : null,
136+
ScenePath = action == Action.Load ? k_PathToLoad : null
137+
});
138+
139+
if (clientType == ClientType.Authority)
140+
{
141+
m_ExpectedEventQueue.Enqueue(new ExpectedEvent()
142+
{
143+
SceneEvent = new SceneEvent()
144+
{
145+
SceneEventType = action == Action.Load ? SceneEventType.LoadComplete : SceneEventType.UnloadComplete,
146+
LoadSceneMode = LoadSceneMode.Additive,
147+
SceneName = k_SceneToLoad,
148+
ScenePath = k_PathToLoad,
149+
ClientId = client.LocalClientId,
150+
}
151+
});
152+
}
153+
154+
m_ExpectedEventQueue.Enqueue(new ExpectedEvent()
155+
{
156+
SceneEvent = new SceneEvent()
157+
{
158+
SceneEventType = action == Action.Load ? SceneEventType.LoadEventCompleted : SceneEventType.UnloadEventCompleted,
159+
LoadSceneMode = LoadSceneMode.Additive,
160+
SceneName = k_SceneToLoad,
161+
ScenePath = k_PathToLoad,
162+
ClientId = m_ServerNetworkManager.LocalClientId,
163+
ClientsThatCompleted = expectedCompletedClients,
164+
ClientsThatTimedOut = new List<ulong>()
165+
}
166+
});
167+
168+
//////////////////////////////////////////
169+
// Testing event notifications
170+
managerToTest.SceneManager.OnSceneEvent += OnSceneEvent;
171+
172+
if (action == Action.Load)
173+
{
174+
Assert.That(m_ServerNetworkManager.SceneManager.LoadScene(loadCall, LoadSceneMode.Additive) == SceneEventProgressStatus.Started);
175+
176+
yield return WaitForConditionOrTimeOut(ValidateSceneIsLoaded);
177+
AssertOnTimeout($"[Test] Timed out waiting for client to load the scene {k_SceneToLoad}!");
178+
}
179+
else
180+
{
181+
Assert.That(loadedScene.name, Is.EqualTo(k_SceneToLoad), "scene was not loaded!");
182+
Assert.That(m_ServerNetworkManager.SceneManager.UnloadScene(loadedScene) == SceneEventProgressStatus.Started);
183+
184+
yield return WaitForConditionOrTimeOut(ValidateSceneIsUnloaded);
185+
AssertOnTimeout($"[Test] Timed out waiting for client to unload the scene {k_SceneToLoad}!");
186+
}
187+
188+
// Wait for all messages to process
189+
yield return s_DefaultWaitForTick;
190+
191+
if (m_ExpectedEventQueue.Count > 0)
192+
{
193+
Assert.Fail($"Failed to invoke all expected OnSceneEvent callbacks. {m_ExpectedEventQueue.Count} callbacks missing. First missing event is {m_ExpectedEventQueue.Dequeue().SceneEvent.SceneEventType}");
194+
}
195+
196+
managerToTest.SceneManager.OnSceneEvent -= OnSceneEvent;
197+
}
198+
199+
private bool ValidateSceneIsLoaded(StringBuilder errorBuilder)
200+
{
201+
var loadedScene = m_ServerNetworkManager.SceneManager.ScenesLoaded.Values.FirstOrDefault(scene => scene.name == k_SceneToLoad);
202+
if (!loadedScene.isLoaded)
203+
{
204+
errorBuilder.AppendLine($"[ValidateIsLoaded] Scene {loadedScene.name} exists but is not loaded!");
205+
return false;
206+
}
207+
if (m_ServerNetworkManager.SceneManager.SceneEventProgressTracking.Count > 0)
208+
{
209+
errorBuilder.AppendLine($"[ValidateIsLoaded] Server NetworkManager still has progress tracking events.");
210+
return false;
211+
}
212+
213+
foreach (var manager in m_ClientNetworkManagers)
214+
{
215+
// default will have isLoaded as false so we can get the scene or default and test on isLoaded
216+
loadedScene = manager.SceneManager.ScenesLoaded.Values.FirstOrDefault(scene => scene.name == k_SceneToLoad);
217+
if (!loadedScene.isLoaded)
218+
{
219+
errorBuilder.AppendLine($"[ValidateIsLoaded] Scene {loadedScene.name} exists but is not loaded!");
220+
return false;
221+
}
222+
223+
if (manager.SceneManager.SceneEventProgressTracking.Count > 0)
224+
{
225+
errorBuilder.AppendLine($"[ValidateIsLoaded] Client-{manager.name} still has progress tracking events.");
226+
return false;
227+
}
228+
}
229+
230+
return true;
231+
}
232+
233+
private bool ValidateSceneIsUnloaded()
234+
{
235+
if (m_ServerNetworkManager.SceneManager.ScenesLoaded.Values.Any(scene => scene.name == k_SceneToLoad))
236+
{
237+
return false;
238+
}
239+
if (m_ServerNetworkManager.SceneManager.SceneEventProgressTracking.Count > 0)
240+
{
241+
return false;
242+
}
243+
244+
foreach (var manager in m_ClientNetworkManagers)
245+
{
246+
if (manager.SceneManager.ScenesLoaded.Values.Any(scene => scene.name == k_SceneToLoad))
247+
{
248+
return false;
249+
}
250+
251+
if (manager.SceneManager.SceneEventProgressTracking.Count > 0)
252+
{
253+
return false;
254+
}
255+
}
256+
return true;
257+
}
258+
259+
private static void ValidateEventsAreEqual(SceneEvent expectedEvent, SceneEvent sceneEvent)
260+
{
261+
AssertField(expectedEvent.SceneEventType, sceneEvent.SceneEventType, nameof(sceneEvent.SceneEventType), sceneEvent.SceneEventType);
262+
AssertField(expectedEvent.LoadSceneMode, sceneEvent.LoadSceneMode, nameof(sceneEvent.LoadSceneMode), sceneEvent.SceneEventType);
263+
AssertField(expectedEvent.SceneName, sceneEvent.SceneName, nameof(sceneEvent.SceneName), sceneEvent.SceneEventType);
264+
AssertField(expectedEvent.ClientId, sceneEvent.ClientId, nameof(sceneEvent.ClientId), sceneEvent.SceneEventType);
265+
AssertField(expectedEvent.ClientsThatCompleted, sceneEvent.ClientsThatCompleted, nameof(sceneEvent.SceneEventType), sceneEvent.SceneEventType);
266+
AssertField(expectedEvent.ClientsThatTimedOut, sceneEvent.ClientsThatTimedOut, nameof(sceneEvent.ClientsThatTimedOut), sceneEvent.SceneEventType);
267+
}
268+
269+
// The LoadCompleted event includes the scene being loaded
270+
private static void ValidateReceivedScene(ExpectedEvent expectedEvent, Scene scene)
271+
{
272+
AssertField(expectedEvent.SceneName, scene.name, "Scene.name", SceneEventType.LoadComplete);
273+
AssertField(expectedEvent.ScenePath, scene.path, "Scene.path", SceneEventType.LoadComplete);
274+
}
275+
276+
private static void AssertField<T>(T expected, T actual, string fieldName, SceneEventType type)
277+
{
278+
Assert.AreEqual(expected, actual, $"Failed on event {s_NumEventsProcessed} - {type}: Expected {fieldName} to be {expected}. Found {actual}");
279+
}
280+
}
281+
}

testproject/Assets/Tests/Runtime/NetworkSceneManager/OnSceneEventCallbackTests.cs.meta

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)