[Netcode] Resolving NetworkManager Shutdown Loop
Solution
Unity 2021.3.x - Unity 6.3.x
Published Wed, Apr 29
When attempting to disconnect and reconnect a client using Netcode for GameObjects and Relay, the NetworkManager.Singleton.ShutdownInProgress property can remain perpetually true. This state prevents subsequent connection attempts. This often occurs when multiple Shutdown() calls are triggered simultaneously, such as when calling it manually while an event callback like OnClientStopped also triggers a secondary, redundant shutdown request.
The persistent NetworkManager.Singleton.ShutdownInProgress state occurs because the internal state machine of the NetworkManager becomes desynchronized during concurrent shutdown requests. To fix this, your script must ensure the shutdown process is atomic and fully completed before resetting your state.
- Create a private boolean flag named shuttingDown to act as a gatekeeper.
- Wrap the
NetworkManager.Singleton.Shutdown()call within aCoroutineto handle the asynchronous cleanup process. - Implement a loop that yields until the
NetworkManagerhas cleared its active status and theShutdownInProgressflag returns to false. - Reset shuttingDown only after the loop exits, ensuring the system is ready for a fresh connection.
This approach prevents redundant calls from OnClientStopped or other event listeners from interfering with the primary shutdown sequence.
Additional Tips:
- Always check if
NetworkManager.Singletonis null before accessing members during a shutdown, as the manager might be destroyed if the scene is changing. - If using the Relay service, ensure you also clean up any active allocations or join codes in your connection manager alongside the shuttingDown logic.
- Avoid calling
Shutdown()insideOnDisablewithout checking the shuttingDown flag, as this can lead to race conditions during application exit.
TL;DR
Implement a custom boolean flag and a Coroutine to ensure the NetworkManager.Singleton.Shutdown method is invoked exactly once and completes fully before allowing new connections.
Related Posts Haven't quite found a solution to your problem? We think these posts might help you.
Content inspired by a Unity discussion post.