This tutorial is about creating, updating and displaying leaderboards for your Android games in Unity. You need to have Google play services set up already if not read our beginners guide to Google play service for Unity.
Setting up Leaderboard in Play console
Login to your Google Play console and select your app.
Click Google Play services and expand setup and configuration.
Select Leaderboard. and click create leaderboard on the right panel.
You should see a window as in the image below.
Fill in the leaderboard name and other details. Click save as draft.
Go back to the leaderboard page using the left panel. You should see the leaderboard details.
Click review and publish on the top.
Sending and receiving scores in Unity
To report a score, you need to add “using UnityEngine.SocialPlatforms” to your code. Then use Social.ReportScore to add the score to your leaderboard. Here is a sample code
Social.ReportScore(Your_score_variable, "Leaderboard_ID", (bool success) => {
if(success)
{
Debug.Log("Score Update");
}
});
To show the default leaderboard UI you can just call
Social.ShowLeaderboardUI();
If you want to display the leaderboard in your UI then you need to load the scores into an array and then display it. To get all the scores use
Social.LoadScores("Leaderboard ID", scores => {});
This will load all the scores into an array.
Get Rank from leaderboard sample code
if(PlayGamesPlatform.Instance.IsAuthenticated())
{
Social.LoadScores("leaderboard_id", scores => {
if (scores.Length > 0)
{
string user=Social.localUser.id;
foreach (IScore score in scores)
{
if(user==score.userID)
{
rank_text.text= "YOUR RANK: "+score.rank.ToString();
}
}
}
});
}
using UnityEngine.SocialPlatforms with an s on the end =)
Hi
Thanks. I have updated the post.