Please help me with KeyNotFoundException - on NetworkServer.connections
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)
Lines of code: In the Playerprefab attached to the network manager:
void Update()
{
if (isServer)
{
for (var i = 0; i < NetworkServer.connections.Count; i++)
{
Debug.Log("Connections: " + NetworkServer.connections[i].identity.netId.ToString());
}
}
}
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.
Answer by ankitpsaraogi · May 26, 2020 at 04:55 PM
I figured it out after nearly pulling all my hair. The solution was so simple and right in front of my eyes.
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());
}
}
}
Your answer
Follow this Question
Related Questions
Sending Rigidbody Position From Server To Client - Unity Network Using Mirror 0 Answers
UNet Sharing Gameobjects between multiple clients 0 Answers
NetworkServer.Send and NetworkClient.Send or synchronising on player prefab? 0 Answers
Spawning Network Objects from the client | Unity Netcode For Gameobjects 0 Answers
Multiplayer - Host can damage client, not vice versa? 1 Answer