当玩家进入房间时执行操作

Perform operation when a player enters the room

我想使用 Photon (Pun2) 创建多人应用程序。玩家加入房间后,我想为该房间中的所有玩家隐藏一些按钮并显示其他按钮。目前我有这个功能:

public override void OnPlayerEnteredRoom(Player newPlayer)
     {
         print(newPlayer); // #02
         if (PhotonNetwork.CurrentRoom.PlayerCount == 2 && PhotonNetwork.IsMasterClient)
         {
             print(PhotonNetwork.CurrentRoom.PlayerCount + "/2 Starting game...");
 
             searchingBtn.SetActive(false); // hide this button
             findMatchBtn.SetActive(false); // hide this button
             scanningBtn.SetActive(true); // display this button
         }
     }

但这行不通,因为只有 2 个玩家中的 1 个按钮会改变,而另一个按钮将保持不变。

我在网上看到一些例子,在这个函数中OnPlayerEnteredRoom它被称为PhotonNetwork.LoadLevel(scene_index),但是那一刻,我不想加载另一个场景,我想留在当前场景和 hide/display 一些按钮。这可能吗?

编辑:这是最终版本

public override void OnJoinedRoom()
{
    Debug.Log("You joined the room.");
    Debug.Log(PhotonNetwork.CurrentRoom.PlayerCount);
    Debug.Log(PhotonNetwork.IsMasterClient);

    UpdateButtons();
}

public override void OnPlayerEnteredRoom(Player newPlayer)
{
    Debug.Log("Other players joined the room.");
    if (PhotonNetwork.CurrentRoom.PlayerCount > 1 && PhotonNetwork.IsMasterClient)
    {
        Debug.Log(PhotonNetwork.CurrentRoom.PlayerCount + "/2 Starting game...");

        UpdateButtons();
    }
}

private void UpdateButtons()
{
    searchingBtn.SetActive(false); // hide this button
    findMatchBtn.SetActive(false); // hide this button
    scanningBtn.SetActive(true); // display this button
}

来自 Photon 文档:

virtual void OnJoinedRoom ()
    //Called when the LoadBalancingClient entered a room, no matter if this client 
    //created it or simply joined.
virtual void OnPlayerEnteredRoom (Player newPlayer)
    //Called when a remote player entered the room. This Player is already added to 
    //the playerlist.

据此,OnPlayerEnteredRoom 仅在远程玩家加入房间时调用。因此,为了解决您的问题,您需要在本地客户端的 OnJoinedRoom 回调中调用您的代码,并在远程玩家加入时 OnPlayerEnteredRoom 调用您的代码。

总而言之,您的新代码应如下所示:

public override void OnPlayerEnteredRoom(Player newPlayer)
{
     UpdateButtons(newPlayer);
}

public override void OnJoinedRoom(Player player)
{
    UpdateButtons(player);
}

private void UpdateButtons(Player player)
{
    if (PhotonNetwork.CurrentRoom.PlayerCount > 1 && PhotonNetwork.IsMasterClient)
    {             
        print(PhotonNetwork.CurrentRoom.PlayerCount + "/2 Starting game...");
 
        searchingBtn.SetActive(false); // hide this button
        findMatchBtn.SetActive(false); // hide this button
        scanningBtn.SetActive(true); // display this button
    }
}