Click here to Skip to main content
15,885,366 members
Articles / Game Development / Unity
Article

Unity on Azure PlayFab Part 6: Leaderboards Made Easy

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
21 Feb 2022CPOL4 min read 5.2K  
This article will demonstrate how to leverage the PlayFab Unity SDK’s built-in features to add a leaderboard to our game.

This article is a sponsored article. Articles such as these are intended to provide you with information on products and services that we consider useful and of value to developers

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.

Image 1

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.

Image 2

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.

Image 3

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:

C#
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."

C#
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 )
{
    // Successfully Reported
}


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:

C#
// Update the status with local game state
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.

Image 4

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:

C#
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:

C#
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.

Image 5

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:

C#
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.

This article is part of the series 'Unity On Azure PlayFab View All

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Raphael Mun is a tech entrepreneur and educator who has been developing software professionally for over 20 years. He currently runs Lemmino, Inc and teaches and entertains through his Instafluff livestreams on Twitch building open source projects with his community.

Comments and Discussions

 
-- There are no messages in this forum --