Google Play Store Leaderboard Integration


This month we integrated our newest game The Dog Run with the Google Play Store Leaderboard service.  It looks, and possibly even should have been, really easy but in this reality it wasn’t.  One big problem that  was really time consuming was that we used the Google key signing service and then had an issue with our key.  Bit I think I’ll describe that in a separate post as it probably deserves more info that we got space for here and wasn’t really what this post is all about.

This post is a about how we integrated our game with the Google Play Store Leaderboard!

(The game has gone into Beta Testing if you would like a preview click the link here!)

First of all – do the research! Read the documentation and look at some tutorials. I found the documentation for the Plugin to be useful and this tutorial to be of the most help (thanks AppGuruz):

http://www.theappguruz.com/blog/leaderboard-setup-for-android-in-unity

But this is how we did it…

1.  To start with you have to be logged in to your Unity account when you open up your project in the Unity Editor.  You will need it to authorise stuff.

2.  Next you will need to import a copy of the Google Play Games plugin for Unity. This is an open-source project which integrates the Google Play Games API with Unity. (Disclaimer: it’s not endorsed or supervised by Unity Technologies).

This is the latest version I used and if you click on the image it will take you there.

The README.md in the repository has a pretty good summary of how to set it up and configure it and examples of how to call features and functions.

The plugin supports a heap of things:

Achievements
Leaderboards
Turn-based Multiplayer
Real-time Multiplayer
Events and Quests
Saved Games and
Nearby Connections

All we wanted was the Leaderboard so let’s start there.

3.  Import the package in the Unity Editor

Assets > Import Package > Custom Package

4.  Then open the Google Play Games Window in the Editor that will appear after you import the package.

Window > Google Play Games > Setup (Android Setup on my machine)

In the Android Setup you will put your Resource Definitions (we only had one for the leaderboard).

I’ll get to how we set up the Resources in the Google Play Console further down but this is what it looks like completed:

(The info in this screenshot is a dummy record so I didn’t have to redact anything for security)

5. Click On “Open Play Games Console” – it’s the blue highlighted link in the Android Configuration page above.

6. Go to the Development tools section and find the Google Play game services section.

7.  Click on the Game services section link

Right down the bottom will be this section confirming your API service:

8.  Find the Service in the list of Services and click on Manage this API (if you need to set up more services):

9.  Right there after drilling down through all those pages you will find your resources:

See that blue link there that says “Get Resources” – that’s your baby.  Once you click on that there are four tabs with a variety of formats.  You want the one that’s there by default for Android.  Take a copy of that xml and paste it into your Androind Setup/Configuration page in your project and your halfway there.    🙂

Now for the fun bit of configuring and scripting it for the game.

There is a bit of trial and error and unless you can connect up an Android device and actively debug through the console using that device there is a long iteration cycle for testing.  From within the editor you cannot test any of the functionality such as logging in as the Google Play Games user and opening the Leaderboard. You have to have the APK loaded up to the Google Play Store and in an Alpha Release Track to start testing.  The package has to be signed using a full key (ie. not the default debug one) and you need to install the package on to your test Android device from the Play Store so that it has the correct keys to work. You cannot build it locally and run it straight from your workstation.  The other thing is that in the Alpha Track the Leaderboard functionality can sometimes be really slow and sometimes just doesn’t load so because of that you need to be patient when testing.

To get this working in my game I created an empty game object and attached this script to it:


using UnityEngine;
using GooglePlayGames;

public class GPG : MonoBehaviour
{
    #region PUBLIC_VAR
    public string leaderboard;  // This is where to pass the resource string in!
    #endregion
    #region DEFAULT_UNITY_CALLBACKS
    public long my_score;  // This is where I passed in the users score
    public bool success;
    public bool GPGLoginReturned;

void Start()
    {
        PlayGamesPlatform.Activate();
        LogIn();
    }
    #endregion
    #region BUTTON_CALLBACKS

// Login to Google Account
public bool LogIn()
    {
        Social.localUser.Authenticate((success) =>
        {
            if (success)
            {
                string userInfo = "Username: " + Social.localUser.userName +
                    "\nUser ID: " + Social.localUser.id +
                    "\nIsUnderage: " + Social.localUser.underage;
            }
            else
            {
                Debug.Log("Login failed");
            }
        });
        return GPGLoginReturned = true;
    }


// Show All Leaderboards
public void OnShowLeaderBoard()
    {
        Social.ShowLeaderboardUI();
    }
	
// Adds a Score to the Leaderboard	
public void AddScoreToLeaderBoard(long my_score)
    {
        if (Social.localUser.authenticated)
        {
            Social.ReportScore(my_score, leaderboard, (bool success) =>
            {
                if (success)
                {
                    Debug.Log("Update Score Success");
                }
                else
                {
                    Debug.Log("Update Score Fail");
                }
            });
        }
    }

// Logout the Google+ Account
public void OnLogOut()
    {
        ((PlayGamesPlatform)Social.Active).SignOut();
    }
    #endregion
}

That basically handles all the interaction with the Google Play Services like user logon and off, showing the leaderboard, and updating the leaderboard. It’s about as simple as you can get.

To update an actual score during gameplay I added this code to the relevant section of the game:


if (!score_uploaded)
{
//AddScoreToLeaderBoard()
var gpg_Script = GPGObject.GetComponent();
long longScore = System.Convert.ToInt64(score_timenow);
gpg_Script.AddScoreToLeaderBoard(longScore);
score_uploaded = true;
}

And to show the Leaderboard I attached and exposed this method to a button call.


OnShowLeaderBoard()

That’s pretty much it. But factor in more time that you think.
It took me ten package builds and releases to get it right – hopefully you won’t have that much trouble.


One response to “Google Play Store Leaderboard Integration”

  1. I used this article again with a new project and got this error when importing the Play Store package: Assets/GooglePlayGames/Editor/GPGSUtil.cs(452,57): error CS0122: `UnityEditor.BuildPipeline.GetPlaybackEngineDirectory(UnityEditor.BuildTarget, UnityEditor.BuildOptions)’ is inaccessible due to its protection level.

    To resolve it I deleted the manifest.json in the Packages folder from the Unity Project structure. Worked automatically after that.

Leave a Reply

Your email address will not be published. Required fields are marked *