In this article, we’ll learn to configure a leaderboard for our Unity game project and report statistics to the PlayFab server to be part of the leaderboard.
Here, we’ll add leaderboard functionality to our Unity game project so far with just a few easy code snippets and no server configuration or maintenance.
Welcome to the finale of this series on PlayFab with Unity! We’ll wrap up this project by setting up a leaderboard to the code from the previous article.
Requirements
Following this guide requires a PlayFab account and the following software:
Mission Briefing
Building leaderboards using player statistics can be challenging. We make sure the data is quickly and globally available, updatable, and available to query. Lucky for us, PlayFab handles the hard parts: We just use their API! In this final part of the series, we’ll create a leaderboard for the number of bots destroyed by each player across the different game sessions.
Creating a Leaderboard
We start by opening the PlayFab dashboard, navigating to Engage > Leaderboards, and clicking New leaderboard.
We set the Statistic Properties to create a Sum leaderboard that tracks the number of bots destroyed. The Statistic name must match the name set in the player’s stats data.
We need to do one more thing in the Dashboard for this tutorial. Multiplayer games usually update these statistics from the server since it can verify certain gameplay conditions and mitigate player cheating using the network. However, we want to push the bot destruction count directly from the game client for simplicity, as manipulated statistics aren’t a big concern for this project.
We select the gear icon to open the Title settings page and click the API Features tab. Then we enable the Allow client to post player statistics option and click Save.
Reporting Statistics from the Client
Next, we need to update the client code to report bot destruction statistics to PlayFab.
We open the Client.cs script and add a new using
statement:
using PlayFab.ClientModels;
We add these three methods to the class to report the event to the server. We need to be sure to match the StatisticName
with the name set in the leaderboard when we created it. It should be something like "Bots Destroyed."
private void ReportStatBotDestroyed()
{
UpdatePlayerStatisticsRequest requestData = new UpdatePlayerStatisticsRequest() {
Statistics = new List<StatisticUpdate>() {
new StatisticUpdate() { StatisticName = "Bots Destroyed", Value = 1 }
}
};
PlayFabClientAPI.UpdatePlayerStatistics( requestData, OnReportStatBotDestroyedResult, OnReportStatBotDestroyedError );
}
private void OnReportStatBotDestroyedResult( UpdatePlayerStatisticsResult response )
{
}
private void OnReportStatBotDestroyedError( PlayFabError error )
{
Debug.Log( error.ErrorMessage );
}
Then inside the Update
loop, we call ReportStatBotDestroyed
where GameObjects
updates the local game state like this:
for( var i = 0; i < enemies.Length; i++ )
{
if( enemyStatus[ i ] > 0 &&
( enemies[ i ] == null || !enemies[ i ].activeSelf ) )
{
enemyStatus[ i ] = 0;
ReportStatBotDestroyed();
}
}
This is all we need to start adding players onto a leaderboard! However, we’ll notice when we open the leaderboard on the Dashboard that all the usernames show up as IDs. It would be better and more personal for the leaderboard to use actual usernames.
If you’d like to see the full code for the Client script, you can find it here.
Setting the Display Name
To change the leaderboards to use names instead of IDs, we need to add one more PlayFab API call to the code.
We open the PlayFabCode.cs script with the login code and add the following methods:
private void SetDisplayNameForUser( string name )
{
UpdateUserTitleDisplayNameRequest requestData = new UpdateUserTitleDisplayNameRequest() {
DisplayName = name
};
PlayFabClientAPI.UpdateUserTitleDisplayName( requestData, OnSetDisplayNameForUserResult, OnSetDisplayNameForUserError );
}
private void OnSetDisplayNameForUserResult( UpdateUserTitleDisplayNameResult response )
{
}
private void OnSetDisplayNameForUserError( PlayFabError error )
{
Debug.Log( error.ErrorMessage );
}
Then at the end of both OnRegisterSuccess
and OnLoginSuccess
, we can set the display name using the Username
field like this:
private void OnLoginSuccess(LoginResult result)
{
ErrorMessage.text = "";
RequestMatchmaking();
SetDisplayNameForUser( Username.text );
}
Now, when we play the game with the same accounts, the displays update.
The full code for PlayFabCode.cs is available here.
Extra: Getting Leaderboard Data
We’ll finish this series with one final snippet of code to show how to retrieve leaderboard data. This way, if we want to show a leaderboard in our game, we can!
We use the following three methods in the Client script to download the leaderboard from PlayFab:
private void GetLeaderboardData()
{
GetLeaderboardRequest requestData = new GetLeaderboardRequest() {
StatisticName = "Bots Destroyed",
StartPosition = 0,
MaxResultsCount = 100,
};
PlayFabClientAPI.GetLeaderboard( requestData, OnGetLeaderboardDataResult, OnGetLeaderboardDataError );
}
private void OnGetLeaderboardDataResult( GetLeaderboardResult response )
{
foreach( var entry in response.Leaderboard )
{
Debug.Log( entry.Position + ". " + entry.DisplayName + " : " + entry.StatValue );
}
}
private void OnGetLeaderboardDataError( PlayFabError error )
{
Debug.Log( error.ErrorMessage );
}
Next Steps
And there it is. On top of enabling players to join and play together, we can now let them compete on a leaderboard.
This concludes this series on building multiplayer features into Unity projects using PlayFab. But there’s still more to explore with PlayFab’s API. To check it out and learn more, look at the PlayFab Documentation. I encourage you to especially check out the Economy and User-Generated Content features, as well as the insight that PlayFab’s analytics can provide.
I hope you enjoyed this series. Good luck with your game development!
To learn more about Azure PlayFab Analytics, and get overviews of features, quickstart guides, and tutorials, check out Azure PlayFab Analytics documentation.