Search code examples
unity-game-enginephoton

Display Another Player's Scores


I made a simple multiplayer quiz game. At the end of the quiz I want to display the scores of both players. Is it possible to get PlayerPrefs value from another player? I use Photon PUN.


Solution

  • Well yes sure it is!

    You could send a simple request RPC like e.g.

    // 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}!");
        }
    }