'How to stop host or client in unity netcode?

When I disconnect my server and go to the menu scene, there comes two NetworkManager Objects but a they are implementing the Singleton pattern and it in itself means that this prescense of two same objects should not happen.

Then I tried to manually destroy the NetworkManager upon disconnecting and it works fine for client but only for one time (upon first disconnecting only) and when furthur the client connects (Here client is connecting the lobby which is a different scene) it throws some errors and is not able to leave the scene again and for server side this does'nt even work once.

This is the error messages I get in the client instance upon reconnecting second time -:

enter image description here

This is Server disconnect code -:

public void OnServerDisconnect()
{
    if (!IsServer) { return; }
    List<NetworkClient> connectedPlayers = (List<NetworkClient>)NetworkManager.Singleton.ConnectedClientsList;


    for (int i = 0; i < connectedPlayers.Count; i++)
    {
        NetworkClient player = connectedPlayers[i];
        if(player.ClientId == NetworkManager.Singleton.ServerClientId) { continue; }
        else
        {
            ClientData.Remove(player.ClientId);
            ChangeClietSceneClientRpc();
        }
    }


    ClientData.Remove(NetworkManager.Singleton.ServerClientId);
    NetworkManager.Singleton.Shutdown(true);
    Destroy(NetworkManager.Singleton.gameObject);
    SceneManager.LoadScene("StartScene", LoadSceneMode.Single);
}

[ClientRpc]
private void ChangeClietSceneClientRpc()
{
    if (IsHost) { return; }

    NetworkManager.Singleton.Shutdown(true);
    Destroy(NetworkManager.Singleton.gameObject);
    SceneManager.LoadScene("StartScene", LoadSceneMode.Single);
}

This is Client disconnect code -:

public void OnClientDisconnect(ulong clientId)
{
    if (!IsServer) { return; }
    else
    {
        ClientData.Remove(clientId);
        ChangeClietSceneClientRpc();
    }

}


Solution 1:[1]

This error occured when your network object was not instantiate through NetworkObject.Spawn() (if you are not using the latest netcode version). I have made a few test about client disconnect and reconnect as well. I found out that in netcode preview 5, all network object which were originally put in the scene will be able to connect and synchornize at the first time, but will lost connection once client trying to reconnect it. This error will no longer appear when I test it in preview 8.

Not sure whether this is your situation, but you can give it a try.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gooddereklu