【问题标题】:In unity, How to fix KeyNotFoundException - on NetworkServer.connections?团结一致,如何在 NetworkServer.connections 上修复 KeyNotFoundException?
【发布时间】:2020-05-26 16:10:55
【问题描述】:

代码:

 void Update()

 {
     if (isServer)
     {

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

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

错误 KeyNotFoundException:给定的键不在字典中。 System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at :0) PlayerManager.Update () (at Assets/Scripts/PlayerManager.cs:504)

当我运行两个构建实例并且其中一个作为主机+客户端运行而其他作为客户端运行时,我发现那里没有问题。它运行良好。它给了我两个值作为输出。

当我仅作为服务器运行时,什么也没有发生,但是一旦我作为客户端运行另一个构建,它就会开始出现上述错误。

我也尝试逐行调试,但 Visual Studio 在调试时没有显示错误。

【问题讨论】:

    标签: unity3d networking client-server multiplayer mirror


    【解决方案1】:

    我想通了。 NetworkServer.Connection 字典将键 0 分配给 Host+Client 但是如果服务器只是充当服务器,它不会为键 0 分配任何值。它从 1 开始对所有客户端。因此,只有在服务器同时作为主机和客户端时才使用 0。

    修改后的代码如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多