Skip to content

Player statistics

Jiufen edited this page Apr 1, 2021 · 3 revisions

Up next, we will see the player statistics. This one is pretty simple, there are 2 methods, one for posting the stats and one for getting the stats.

⏫Posting Stats⏫

For posting stats we will use the next method:

public void UploadStats() {
    PlayFabClientAPI.UpdatePlayerStatistics(new UpdatePlayerStatisticsRequest
    {
        // request.Statistics is a list, so multiple StatisticUpdate objects can be defined if required.
        Statistics = new List {
            new StatisticUpdate { StatisticName = "PlayerHealth", Value = playerHealth },
            new StatisticUpdate { StatisticName = "PlayerLevel", Value = playerLevel },
            new StatisticUpdate { StatisticName = "MaxScore", Value = maxScore },
        }
    },
    result => { Debug.Log("User statistics updated"); },
    error => { Debug.LogError(error.GenerateErrorReport()); });
}

Remember that in order to use this method you will hace to activate the next settings in the playfab dashboard:

⏬Getting Stats⏬

For gettin stats we will use the next methods:

public void GetStats() {
    PlayFabClientAPI.GetPlayerStatistics(
        new GetPlayerStatisticsRequest(),
        OnGetStatistics,
        error => Debug.LogError(error.GenerateErrorReport())
    );
}
public void OnGetStatistics(GetPlayerStatisticsResult result) {
    Debug.Log("Received the following Statistics:" + result.Statistics.Count);
    foreach (var eachStat in result.Statistics){
        Debug.Log("Statistic (" + eachStat.StatisticName + "): " + eachStat.Value);
        switch(eachStat.StatisticName){
            case "PlayerHealth":
                playerHealth = eachStat.Value;
                Debug.Log("PlayerHealth: "+playerHealth);
                break;
            case "PlayerLevel":
                playerLevel = eachStat.Value;
                Debug.Log("PlayerLevel: "+playerLevel);
                break;
            case "MaxScore":
                maxScore = eachStat.Value;
                Debug.Log("MaxScore: "+maxScore);
                break;
        }
    }
}

Clone this wiki locally