显示其他玩家的分数

Display Another Player's Scores

我做了一个简单的多人问答游戏。在测验结束时,我想显示两位玩家的分数。是否可以从其他玩家那里获取 PlayerPrefs 值? 我使用 Photon PUN。

嗯,是的,当然是!

您可以发送一个简单的请求 RPC,例如

// Pass in the actor number of the player you want to get the score from
public void GetScore(int playerId)
{
    // Get the Player by ActorNumber
    var targetPlayer = Player.Get(playerId);
    // Get your own ID so the receiver of the request knows who to answer to
    var ownId = PhotonNetwork.LocalPlayer.ActorNumber;

    // Call the GetScoreRpc on the target player
    // passing in your own ID so the target player knows who to answer to
    photonView.RPC(nameof(GetScoreRpc), targetPlayer, ownId);
}

[PunRpc]
private void GetScoreRpc(int requesterId)
{
    // Get the requester player via the ActorNumber
    var requester = Player.Get(requesterId);
    // Fetch your score from the player prefab
    // -1 indicates that there was an error e.g. no score exists so far
    // up to you how you deal with that case
    var ownScore = PlayerPrefs.GetInt("Score", -1);
    // Get your own ID so the receiver knows who answered him
    var ownId = PhotonNetwork.LocalPlayer.ActorNumber;

    // Call the OnReceivedPlayerScore on the player who originally sent the request
    photonView.RPC(nameof(OnReceivedPlayerScore),  ownId, ownScore);
}

[PunRpc]
private void OnReceivedPlayerScore(int playerId, int score)
{
    // Get the answering player by ActorNumber
    var player = Player.Get(playerId);

    // Do whatever you want with the information you received e.g.
    if(score < 0)
    {
        Debug.LogError($"Could not get score from player \"{player.NickName}\"!");
    }
    else
    {
        Debug.Log($"Player \"{player.NickName}\" has a score of {score}!");
    }
}