简体   繁体   English

团结一致,如何在 NetworkServer.connections 上修复 KeyNotFoundException?

[英]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.错误 KeyNotFoundException:字典中不存在给定的键。 System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at:0) PlayerManager.Update () (at Assets/Scripts/PlayerManager.cs:504) 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.它给了我两个值 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.我也尝试逐行调试,但 Visual Studio 在调试时没有显示错误。

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. NetworkServer.Connection 字典将键 0 分配给 Host+Client 但如果服务器仅充当服务器,则不会为键 0 分配任何值。对于所有客户端,它从 1 开始。 Hence, 0 will only be used if the server acts as host & client both.因此,仅当服务器同时充当主机和客户端时才使用 0。

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());
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM