Tutorial: GameCenter Leaderboards in 5 minutes! (for intermediate/advanced scripters)

This is assuming you already have your GameCenter activated for your game at developer.apple.com, and never did this, or first time trying out Unity’s Social API and could use a quick 5 minute explanation of how to get this thing working. As of this writing, Unity’s Social API code is incomplete and every user will have to do additional searching to find out how to get the callback working. I’ll have it explained out here for you guys instead.

  1. From Unity’s Social API, copy and paste this code into a empty gameObject that is part of your loading section:
import UnityEngine.SocialPlatforms;

function Start () {
    // Authenticate and register a ProcessAuthentication callback
    // This call needs to be made before we can proceed to other calls in the Social API
    Social.localUser.Authenticate (ProcessAuthentication);
}

// This function gets called when Authenticate completes
// Note that if the operation is successful, Social.localUser will contain data from the server. 
function ProcessAuthentication (success: boolean) {
    if (success) {
        Debug.Log ("Authenticated, checking achievements");

        // Request loaded achievements, and register a callback for processing them
        Social.LoadAchievements (ProcessLoadedAchievements);
    }
    else
        Debug.Log ("Failed to authenticate");
}

// This function gets called when the LoadAchievement call completes
function ProcessLoadedAchievements (achievements: IAchievement[]) {
    if (achievements.Length == 0)
        Debug.Log ("Error: no achievements found");
    else
        Debug.Log ("Got " + achievements.Length + " achievements");

    // You can also call into the functions like this
    Social.ReportProgress ("Achievement01", 100.0, function(result) {
        if (result)
            Debug.Log ("Successfully reported achievement progress");
        else
            Debug.Log ("Failed to report achievement");
    });
}

This is straight from the Social API’s page. Check that page for the C# version. This is what load’s the actual Gamecenter at the start of your game. From here, you will need to link a button to RetrieveHighScores, and calls to PostScores wherever necessary.

  1. Make your RetrieveHighScores button. To do that, first put:

import UnityEngine.SocialPlatforms;

on the top of the script file where your button to retrieve high scores will be. Then, simply have this line of code for the button:

Social.ShowLeaderboardUI();
  1. The final step, posting scores. Basically same as step two, but one extra mandatory error-proofing step:
import UnityEngine.SocialPlatforms; // at the top of the script file where scores will be posting to GC

var scoreLong : long = highScore; // Gamecenter requires a long variable
Social.ReportScore(scoreLong,"yourLeaderboardIDinQuotes",HighScoreCheck);

static function HighScoreCheck(result : boolean) {
	if(result)
		Debug.Log("score submission successful");
	else
		Debug.Log("score submission failed");
}

And that’s it! Just repeat the ReportScore and the additional error-checking function for every variable you want reported to GameCenter. This is just the leaderboards, but once you get the hang of this, adding Achievements or anything else should be a matter of changing up the variables through the Social scripting reference.

6 Likes

Great thanks. Step three submits the player’s score to the leaderboard, right? Also when can we get a leaderboard ID? Do we have to submit our app to the app store first? Thanks

thanks

Is there a way to get an authentication failure message besides that ‘success’ boolean?

thank you!

Will this work today ?
Like after 3 plus years ?

Yes it works perfectly. Thanks for the post!

if you want to retrieve the current user leaderboard’s score

        Social.LoadScores("bestplayersvictory", scores => {
            if (scores.Length > 0)
            {
                Debug.Log("Got " + scores.Length + " scores");

               //idUser is retrieve after authentication
                foreach (IScore score in scores) {
                    if(score.userID == idUser) {
                        Debug.Log(score.value);
                        PlayerPrefs.SetInt("nombreVictoire", Int32.Parse(score.value));
                    }
                }
            }

        });
1 Like

But can you post C# script. I copied this and it show a number of errors???

In case you’re still wondering, you’re probably trying to use c# when the code is probably in javascript :slight_smile:

    // This function gets called when Authenticate completes
    // Note that if the operation is successful, Social.localUser will contain data from the server.
    private void ProcessAuthentication(bool success)
    {
        if (success)
        {
            Debug.Log("Authenticated, checking achievements");

            // Request loaded achievements, and register a callback for processing them
            Social.LoadAchievements(ProcessLoadedAchievements);
        }
        else
            Debug.Log("Failed to authenticate");
    }

    // This function gets called when the LoadAchievement call completes
    private void ProcessLoadedAchievements(IAchievement[] achievements )
    {
        if (achievements.Length == 0)
            Debug.Log("Error: no achievements found");
        else
            Debug.Log("Got " + achievements.Length + " achievements");


        // You can also call into the functions like this
        Social.ReportProgress("Achievement01", 100.0, Report);

    }

    private void Report(bool result)
    {
        if (result)
            Debug.Log("Successfully reported achievement progress");
        else
            Debug.Log("Failed to report achievement");
    }