Home > Blockchain >  Unity: PUN Game Freezes and Cannot Sync Var
Unity: PUN Game Freezes and Cannot Sync Var

Time:03-31

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

Above is the bugged snippet of code. It did not freeze without the WHILE (TRUE) in it. But without it the vars do not sync to new people that join the room. It is meant to sync the playerCount so that not 2 people can be player one.

CodePudding user response:

Remove your while loop and just call your RPC with RPC target 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);
}

All RPCs sent with RpcTarget.*Buffered are cached, meaning they will execute on all currently connected remote machine as well as those who will connect in the future.

  • Related