PlayFab: Load PlayFab Leaderboard Scores in Unity with C#

3/17/2021 5:02:54 PM

Using C# and Unity 3D, load top scores in a PlayFab leaderboard.


void PlayFab__Load_Top_Scores()
{
	if (PlayFabClientAPI.IsClientLoggedIn() == false)
	{		
		return;
	}
	
			
	try
	{
		var max_scores_to_load = 10;
		var leaderboard_name = "High Scores";
		
		var request = new GetLeaderboardRequest() { StartPosition = 0, StatisticName = leaderboard_name, MaxResultsCount = max_scores_to_load };
		PlayFabClientAPI.GetLeaderboard(request, PlayFab__OnSuccessGetLeaderboard, PlayFab__OnErrorGetLeaderboard);
	}
	catch (Exception ex)
	{
		Debug.LogError(ex);
	}
}


void PlayFab__OnSuccessGetLeaderboard(GetLeaderboardResult result)
{
	Debug.Log("PlayFab__OnSuccessGetLeaderboard");

	//do something with each score
	foreach (PlayerLeaderboardEntry player_score in result.Leaderboard)
	{
		Debug.Log(player_score.DisplayName + ": " + player_score.StatValue);
	}

}


void PlayFab__OnErrorGetLeaderboard(PlayFabError result)
{
	Debug.Log("PlayFab__OnErrorGetLeaderboard");
	Debug.LogError(result.ErrorMessage);
}