Search Unity

KeyNotFoundException after host leaves and rehosts

Discussion in 'Netcode for GameObjects' started by Casual909, May 8, 2022.

  1. Casual909

    Casual909

    Joined:
    Mar 3, 2021
    Posts:
    12
    I have been stuck for 2 full days on this super simple use case which I simply can't seem to figure out what I am doing wrong.
    When I try to fire any ClientRCP after rehosting I get a KeyNotFoundException. The cause seems to be the observers in any of the NetworkObjects that I have in my scene. When I open the tab I get spammed with the exact same error as you can see in the image. This only occurs when the host is the first to use NetworkManager.Singleton.Shutdown();

    When the client uses the shutdown() first which refires Leave() to make everyone leave then I can rehost without any issues.

    Code (CSharp):
    1. public void Leave()
    2.     {
    3.         Debug.LogError("DISCONNECTED: " + NetworkManager.Singleton.LocalClientId);
    4.         NetworkManager.Singleton.Shutdown();
    5.  
    6.         if (NetworkManager.Singleton.IsHost)
    7.             NetworkManager.Singleton.ConnectionApprovalCallback -= ApprovalCheck;
    8.  
    9.         rPSManager.OpenJoinUI();
    10.         leaveButton.SetActive(false);
    11.     }
    12.  
    13. public void HandleClientDisconnect(ulong clientId)
    14.     {
    15.         Leave(); //Force all other players to leave and cut connection
    16.     }
    Or is this a very wrong way to handle disconnections?
     

    Attached Files:

  2. Casual909

    Casual909

    Joined:
    Mar 3, 2021
    Posts:
    12
    Solution:


    Context: use this if you don't change scenes unlike in the Boss Room default code example. The NetworkObjects don't remove the client ids properly from their observers when the host calls a shutdown. Hence you gotta disconnect all users first except the host and thereafter disconnect the host through shutdown so the NetworkObjects don't get destroyed en you can make host a new match