Search code examples
unity-game-enginenetworkingclient-servermultiplayerunity3d-mirror

In unity, How to fix KeyNotFoundException - on NetworkServer.connections?


Code:

 void Update()

 {
     if (isServer)
     {

         for (var i = 0; i < NetworkServer.connections.Count; i++)
         {

             Debug.Log("Connections: " + NetworkServer.connections[i].identity.netId.ToString());
         }
     }
 }

Error KeyNotFoundException: The given key was not present in the dictionary. System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at :0) PlayerManager.Update () (at Assets/Scripts/PlayerManager.cs:504)

When I run two instances of the build and one of which runs as host+client and other runs as client, I see no issues there. It is working perfectly. It gives me two values as output.

When I run as server only, nothing happens but as soon as I run another build as client, it starts shooting the above error.

I tried debugging line by line as well but the Visual Studio shows me no error while debugging.


Solution

  • I figured it out. The NetworkServer.Connection dictionary assigns the key 0 to Host+Client But if the server acts only as a server, it does not assign any value to key 0. It starts from 1 for all the clients. Hence, 0 will only be used if the server acts as host & client both.

    The corrected code is as under:

    void Update()
    {
        if (isServer)
        {
            foreach (KeyValuePair<int,NetworkConnectionToClient> item in NetworkServer.connections)
            {
                Debug.Log("Connections--->:" + item.Key + "-->"+item.Value.identity.netId.ToString());
            }
    
        }
    }