Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Resolved Help understanding NetworkSceneManager Scene Validation

Discussion in 'Netcode for GameObjects' started by FelipeCavaco, Mar 16, 2024.

  1. FelipeCavaco

    FelipeCavaco

    Joined:
    Sep 22, 2021
    Posts:
    3
    Hi, I've been trying to convert my local multiplayer game to an online multiplayer experience using NGO, but I'm having trouble understanding how the scene validation on the NetworkSceneManager works...

    To start things off, my game uses a multi-scene structure, so I need to load multiple scenes additively for my game to work. I also have a bootstrap scene that contains a bunch of managers that my game needs (including the NetworkManager) that is always loaded.

    From my understanding, scenes that were already loaded before starting the server will be also loaded on the clients when the client connects, and any scene loaded by the server using the NetworkSceneManager after that is also loaded on all clients.

    Now, reading through the Scene Validation section of the documentation, one of the examples says you can use Scene Validation to check is a scene is already pre-loaded on the client, thus avoiding duplication.

    But here's my problem: The server works as expected, but on the clients, my pre-loaded scenes are being unloaded! And I don't want that, I want to keep the pre-loaded scenes!

    Here's a simplified version of the code I'm using:

    Code (CSharp):
    1. public class MultiSceneManager : MonoBehavior
    2. {
    3.     private NetworkManager NetworkManager => NetworkManager.Singleton;
    4.  
    5.     private void Awake()
    6.     {
    7.         NetworkManager.OnServerStarted += OnServerStarted;
    8.         NetworkManager.OnServerStopped += OnServerStopped;
    9.         NetworkManager.OnClientStarted += OnClientStarted;
    10.         NetworkManager.OnClientStopped += OnClientStopped;
    11.     }
    12.  
    13.     private void OnDestroy()
    14.     {
    15.         if(GameManager.IsQuitting)
    16.             return;
    17.      
    18.         NetworkManager.OnServerStarted -= OnServerStarted;
    19.         NetworkManager.OnServerStopped -= OnServerStopped;
    20.         NetworkManager.OnClientStarted -= OnClientStarted;
    21.         NetworkManager.OnClientStopped -= OnClientStopped;
    22.     }
    23.  
    24.     private void OnServerStarted()
    25.     {
    26.         //The Scene manager only exists when we start a connection
    27.         NetworkManager.SceneManager.OnSceneEvent += OnNetworkSceneEvent;
    28.         NetworkManager.SceneManager.VerifySceneBeforeLoading = NetworkServerSceneValidation;
    29.     }
    30.  
    31.     private void OnServerStopped(bool isHost)
    32.     {
    33.         if(GameManager.IsQuitting)
    34.             return;
    35.      
    36.         NetworkManager.SceneManager.OnSceneEvent -= OnNetworkSceneEvent;
    37.     }
    38.  
    39.     private void OnClientStarted()
    40.     {
    41.         if(NetworkManager.IsServer)
    42.             return;
    43.      
    44.         //The Scene manager only exists when we start a connection
    45.         NetworkManager.SceneManager.OnSceneEvent += OnNetworkSceneEvent;
    46.         NetworkManager.SceneManager.VerifySceneBeforeLoading = NetworkClientSceneValidation;
    47.     }
    48.  
    49.     private void OnClientStopped(bool isHost)
    50.     {
    51.         if(NetworkManager.IsServer)
    52.             return;
    53.      
    54.         NetworkManager.SceneManager.OnSceneEvent -= OnNetworkSceneEvent;
    55.     }
    56.  
    57.     private bool NetworkServerSceneValidation(int sceneIndex, string sceneName, LoadSceneMode loadSceneMode)
    58.     {
    59.         return true;
    60.     }
    61.  
    62.     private bool NetworkClientSceneValidation(int sceneIndex, string sceneName, LoadSceneMode loadSceneMode)
    63.     {
    64.         Debug.Log($"===>  [CLIENT] Trying to load scene {sceneName}");
    65.      
    66.         //Don't not load scenes that are already loaded
    67.         var scene = SceneManager.GetSceneByBuildIndex(sceneIndex);
    68.  
    69.         if (scene.isLoaded)
    70.         {
    71.             Debug.LogWarning($"===>  [CLIENT] Scene {sceneName} is loaded! Thus invalid");
    72.             return false;
    73.         }
    74.  
    75.         Debug.Log($"===>  [CLIENT] Scene {sceneName} is not loaded, thus valid");
    76.         return true;
    77.     }
    78.  
    79.     public void LoadScene(int sceneBuildIndex, LoadSceneMode loadSceneMode)
    80.     {
    81.         //Only the server can load/unload scenes
    82.         if(!(NetworkManager.IsServer || NetworkManager.IsHost))
    83.             return;
    84.  
    85.         var sceneName = GetSceneNameByBuildIndex(sceneBuildIndex);
    86.         var status = NetworkManager.SceneManager.LoadScene(sceneName, loadSceneMode);
    87.  
    88.         if (status != SceneEventProgressStatus.Started)
    89.         {
    90.             Debug.LogError($"Failed to load {sceneName} with a {nameof(SceneEventProgressStatus)}: {status}");
    91.             return;
    92.         }
    93.     }
    94.  
    95.     public void UnloadSceneUsingSceneManager(int sceneBuildIndex)
    96.     {
    97.         //Only the server can load/unload scenes
    98.         if(!(NetworkManager.IsServer || NetworkManager.IsHost))
    99.             return;
    100.  
    101.         var sceneName = GetSceneNameByBuildIndex(sceneBuildIndex);
    102.         var scene = GetSceneByName(sceneName);
    103.         var status = NetworkManager.SceneManager.UnloadScene(scene);
    104.  
    105.         if (status != SceneEventProgressStatus.Started)
    106.         {
    107.             Debug.LogError($"Failed to unload {sceneName} with a {nameof(SceneEventProgressStatus)}: {status}");
    108.             return;
    109.         }
    110.     }
    111.  
    112.     public string GetSceneNameByBuildIndex(int buildIndex)
    113.     {
    114.         var scenePath = SceneUtility.GetScenePathByBuildIndex(buildIndex);
    115.         var sceneName = Path.GetFileNameWithoutExtension(scenePath);
    116.         return sceneName;
    117.     }
    118.  
    119.     public Scene GetSceneByName(string sceneName)
    120.     {
    121.         return SceneManager.GetSceneByName(sceneName);
    122.     }
    123.  
    124.     private void OnNetworkSceneEvent(SceneEvent sceneEvent)
    125.     {
    126.         switch (sceneEvent.SceneEventType)
    127.         {
    128.             case SceneEventType.Load:
    129.                 if (sceneEvent.ClientId == NetworkManager.LocalClientId)
    130.                 {
    131.                     Debug.Log($"===> NetworkScene {sceneEvent.SceneName} loading started");
    132.                     _networkOperation = sceneEvent.AsyncOperation;
    133.                 }
    134.                 break;
    135.             case SceneEventType.Unload:
    136.                 if (sceneEvent.ClientId == NetworkManager.LocalClientId)
    137.                 {
    138.                     Debug.Log($"===> NetworkScene {sceneEvent.SceneName} unloading started");
    139.                     _networkOperation = sceneEvent.AsyncOperation;
    140.                 }
    141.                 break;
    142.             case SceneEventType.LoadEventCompleted:
    143.                 Debug.Log($"===> NetworkScene {sceneEvent.SceneName} loaded");
    144.                 break;
    145.             case SceneEventType.UnloadEventCompleted:
    146.                 Debug.Log($"===> NetworkScene {sceneEvent.SceneName} unloaded");
    147.                 break;
    148.             case SceneEventType.LoadComplete:
    149.                 if (sceneEvent.ClientId == NetworkManager.LocalClientId)
    150.                 {
    151.                     Debug.Log($"===> NetworkScene {sceneEvent.SceneName} loading completed");
    152.                     _networkOperation = null;
    153.                 }
    154.                 break;
    155.             case SceneEventType.UnloadComplete:
    156.                 if (sceneEvent.ClientId == NetworkManager.LocalClientId)
    157.                 {
    158.                     Debug.Log($"===> NetworkScene {sceneEvent.SceneName} unloading completed");
    159.                     _networkOperation = null;
    160.                 }
    161.                 break;
    162.             default:
    163.                 throw new ArgumentOutOfRangeException();
    164.         }
    165.     }
    166. }
    167.  

    I've tried mixing and matching who does the validation, but nothing I did worked:
    • If I return true on both validations, existing scenes gets duplicated for a second, and the everything gets unloaded EXCEPT the ones loaded after the server started;
    • If I return true on the server but do the validation in the client (like in the code above), Apparently I don't get the duplication, but all scenes are unloaded except for the ones that were loaded after the server started;
    • If I do the validation on the server but return true on the client, nothing get loaded nor unloaded, so basically nothing changes;
    • If I do the validation on both sides, again nothing gets loaded nor unloaded.

    So, what am I doing wrong?
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    6,922
    I haven't used this before so I'm just going to throw out some expectations, hoping that it helps. ;)

    First, it's important to note what exactly is the state when you call StartServer/StartHost. All of these scenes get synchronized to the client. And I believe there is no way of going around that to actually keep already loaded scenes on the client in that case - I may be wrong though, it's just an expectation. At the very least, any already-loaded scenes on the client will not be networked.

    The clients are free to load additional additive scenes after they joined a network session however.

    To avoid complications regarding scene manager I think the best solution is to always single-load a specific game scene on the server right after you called StartServer/StartHost. The clients tag along with that scene load and can then additively load local-only scenes, such as GUI.

    Now whenever a client (including the host) leaves, then the next thing I do is to single-load the non-game scene. Typically that will be a menu scene. So you basically switch between an offline and an online scene, where you start a new online session in the offline scene. The dedicated server can remain in the online scene, provided state reset is performed particularly when all clients have left since the new clients joining from then on may want to start with a clean slate (it's a new "session").

    Lastly, the Active Scene Synchronization is perhaps what you may need to disable to make clients keep their already loaded scenes. However, this would seem to require more work to synchronize any networked scenes, at the least by instructing clients to load specific network scenes via RPCs.

    PS: also try asking in the multiplayer discord channel since there are very active, knowledgable people around.
     
  3. FelipeCavaco

    FelipeCavaco

    Joined:
    Sep 22, 2021
    Posts:
    3
    @CodeSmile Thanks for the answer. This wasn't the answer I was looking for but fortunately I've figured it out.

    As you mentioned, though, pre-loaded scenes are not synchronized, but in my case I don't need them to be, I just need them to exist.

    As for the unloading of pre-loaded scenes, in the Client Synchronization Mode page it's explained that by default it uses LoadSceneMode.Single, which will unload any pre-loaded scenes in the client during the syncronization step. I had to change the NetworkSceneManager.SetClientSynchronizationMode to LoadSceneMode.Additive and the NetworkSceneManager.PostSynchronizationSceneUnloading to false for it to keep my scenes loaded, and I can even set the NetworkSceneManager.VerifySceneBeforeUnloading callback to do a validation on which scenes actually gets unloaded.
     
    Last edited: Mar 18, 2024
    ankofl_unity and CodeSmile like this.