Unity:PUN 游戏冻结且无法同步 Var

Unity: PUN Game Freezes and Cannot Sync Var

public override void OnJoinedRoom()
    {
        GUI.enabled = false;
        Debug.Log("ROOM ACTIVE");
        photonView.RPC("NewPlayer", RpcTarget.All, true);
        playerNum = playerCount;
        while (true)
        {
            pause(newPlayerJoined);
            photonView.RPC("BroadcastPlayerNum", RpcTarget.All, playerCount);
        }
    }

    public IEnumerable pause(bool x)
    {
        yield return new WaitUntil(() => x);
    }
    public override void OnLeftRoom()
    {
        photonView.RPC("LeftPlayer", RpcTarget.All, true);
    }

    [PunRPC]
    void NewPlayer(bool AddToCount)
    {
        if (AddToCount)
        {
            playerCount += 1;
            newPlayerJoined = true;
        }
    }

    void LeftPlayer(bool AddToCount)
    {
        if (AddToCount)
        {
            playerCount -= 1;
        }
    }

    void BroadcastPlayerNum(int x)
    {
        playerCount = x;
    }

以上是有问题的代码片段。如果其中没有 WHILE (TRUE),它不会冻结。但如果没有它,vars 就不会同步到加入房间的新人。它的目的是同步 playerCount,以便不是 2 个人可以成为玩家。

删除你的 while 循环,只用 RPC 目标调用你的 RPC RpcTarget.AllBuffered

public override void OnJoinedRoom()
{
    GUI.enabled = false;
    Debug.Log("ROOM ACTIVE");
    photonView.RPC("NewPlayer", RpcTarget.All, true);
    playerNum = playerCount;
    photonView.RPC("BroadcastPlayerNum", RpcTarget.AllBuffered, playerCount);
}

所有使用 RpcTarget.*Buffered 发送的 RPC 都被缓存,这意味着它们将在所有当前连接的远程计算机以及将来连接的远程计算机上执行。