In part 2 of our Unity Gaming Services tutorial series we introduced the Authentication package, and in part 3, showed you how to implement Facebook sign-in in your project. In this post, part 4, you’ll learn how to implement Google Play, the recommended recoverable method that comes with all Android phones.
Where to find all of the content in the Unity Gaming Services tutorial series
The UGS series consists of 10 sets of tutorials, with each set comprising a video and written tutorial.
Video tutorials
The full video tutorial series will be here. We’ll add the video tutorials to this playlist throughout October.
Written tutorials
You’ll find links to all articles in this series as they become available in Part 1, the introduction post.
Demo project and scripts
You can find the Gem Hunter Match – Cloud Edition demo project in the GitHub page.
The scripts used in the tutorials can be downloaded here:
UGSTutorialSeries_Scripts.zip (1.6 MB)
You can watch the video version of this tutorial on Unity’s Youtube channel:
In this tutorial, you’ll continue to work on the simple project from previous posts, which so far consists of simple UI buttons and a LoginManager script to handle all of the login or linking to providers. As before, you’ll also continue to use the code examples provided in UGS documentation.
Plugin and dashboard setup
Click here to get the latest version of the Unity plugin by Google, which you can then add to your project via Assets > Import Package > Custom Package.
Among the files imported to the project will be some ExternalDependencyManager files; if you get prompted about deleting obsolete files in your project click Apply.
Go to the Google Play Console. You’ll need a developer account and a game created (your own project); once you create one, go to Grow users > Play Games services > Setup and management > Configuration and click on Create a new Cloud project.
Click on Done.
This takes you to a new dashboard, the Google Cloud Console. Create a Project name and leave Location as No organization.
Under APIs & Services create an OAuth consent screen and fill in the information. For Audience, select External since you don’t have an organization.
When you are done there, head back to the previous tab in the Google Play Console and in the applicable field, select the Cloud project that you created in the previous step.
Click Use to see your progress on the integration of Google Play services.
The next step is to create credentials; scroll down and in the credentials sections click Add credentials.
Select Game server, and then the Create OAuth client option as seen in the above screenshot. When you click this option you’ll get the details you’ll need to use in the Google Cloud Console.
In the console, select Clients > Create OAuth client ID. Then, select Web application, select a name for the client, and click Create.
Now you can see your client in the list.
Finally, in the Google Play Console, select your newly created client.
Click Save changes. Notice that the credentials were added to the Google Play Console. Now, you need to repeat the process of creating a client, this time for Android.
In the Google Cloud Platform, select the Android application type, and in the Package name field, add the one matching your project settings. You need to make a keystore to verify the authenticity of your app.
At this point, jump into your project in Unity, and go to Project settings > Player > Publishing settings. Click on Keystore Manager. In the pop-up window, select Create new > In Dedicated Location.
Remember the location where you save it as you will need it later. Add a new password in the Enter keystore password field and use this same password in the New Key Values field as well.
With the keystore created, populate the information in the Publishing Settings fields.
Now you are ready to add the last information remaining in the new Android client window of the Google Cloud Console.
The easiest way to modify the command with your keystore path is to copy and edit it in a text editor. It should look like this.
Indicate in the Command Prompt on Windows or Terminal on Mac that you are looking for the SHA1 line.
If you had issues on Windows, you can try running the terminal from the Java folder, by entering first: cd C:\Program Files\Java\jr…\bin.
Now paste the SHA1 fingerprint.
Now that we have the Android client created, let’s add the credential selecting this OAuth client.
Adding testers
In the Google Play Console under Grow users > Play Games services > Setup and management > Testers you can add any users identified in your Android phone to test during development.
One last step: Resources Definition
To finalize the set up, go to Windows > Google Play Games > Setup > Android setup.
You need to introduce the resources definition that you will get from the Google Play Console. Go to the configuration section again and click Get resources.
Copy the XML in there and paste it into Unity in the Resources Definition field.
In the Google Play console, go to Game server > Configuration. From here, you can find the Client ID to add to the Android Setup.
Lastly, in your Unity project, go to Nearby Connections setup via Google Play Games > Setup. A success message should confirm that Nearby Connections were configured successfully.
Project setup
As with the other identity providers, back in the Editor, you need to add Google Play Games from either the Unity Dashboard or Authentication in Project Settings.
For the required fields, Client ID and Client Secret can both be found in the Google Cloud Console. Inside the console, check for Client, and select the web client.
When you have added them to the identity provider, click Save.
The last pending item in the checklist is to add the SDK to the build, which is the APK file.
If you click the item it will take you to the documentation on how to integrate the SDK.
Open the main template inside Assets > Plugins > Android.
Replace the selected line that has :pgs-plugin-support: in it with the one from the SDK docs that includes :play-services-games-v2.
Sign in and link with Google Play Games
Now open the LoginManager that you have been working on. Here again, you’ll use the code from the documentation.
First you need to add the directives but only when building for Android, so add that at the top.
#if UNITY_ANDROID
using GooglePlayGames;
using GooglePlayGames.BasicApi;
#endif
Then create a variable to store the authentication token that will be used by Unity’s authentication services.
private string m_GooglePlayGamesToken;
In the Awake method activate the plugin, and initialize Google Play with your method LoginGooglePlayGames(). Optionally, enable debug log for development purposes.
#if UNITY_ANDROID
PlayGamesPlatform.DebugLogEnabled = true;
// Initialize PlayGamesPlatform
PlayGamesPlatform.Activate();
LoginGooglePlayGames();
#endif
Your method initializes the authentication flow with Google Play Games and if successful you request the token. Then, proceed to start the sign-in process, and as you did previously, check the user status; if the user is signed in link the account, if not, then sign in with Google Play Games.
The complete method to add in your LoginManager looks like this:
#if UNITY_ANDROID
public void LoginGooglePlayGames()
{
PlayGamesPlatform.Instance.Authenticate((status) =>
{
if (status == SignInStatus.Success)
{
Debug.Log("Login with Google Play games successful.");
PlayGamesPlatform.Instance.RequestServerSideAccess(true, code =>
{
Debug.Log("Authorization code: " + code);
m_GooglePlayGamesToken = code;
// This token serves as an example to be used for SignInWithGooglePlayGames
});
}
else
{
Debug.Log($"Google Play Games login unsuccessful, status: {status}");
}
});
}
public void StartSignInWithGooglePlayGames()
{
if (!PlayGamesPlatform.Instance.IsAuthenticated())
{
Debug.LogWarning("Not yet authenticated with Google Play Games -- attempting login again");
LoginGooglePlayGames();
return;
}
SignInOrLinkWithGooglePlayGames();
}
private async void SignInOrLinkWithGooglePlayGames()
{
if (string.IsNullOrEmpty(m_GooglePlayGamesToken))
{
Debug.LogWarning("Authorization code is null or empty!");
return;
}
if (!AuthenticationService.Instance.IsSignedIn)
{
await SignInWithGooglePlayGamesAsync(m_GooglePlayGamesToken);
}
else
{
await LinkWithGooglePlayGamesAsync(m_GooglePlayGamesToken);
}
}
private async Task SignInWithGooglePlayGamesAsync(string authCode)
{
try
{
await AuthenticationService.Instance.SignInWithGooglePlayGamesAsync(authCode);
Debug.Log("Sign in with Google Play Games is successful.");
PlayerSignedIn.Invoke();
}
catch (AuthenticationException ex)
{
// Compare error code to AuthenticationErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
catch (RequestFailedException ex)
{
// Compare error code to CommonErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
}
private async Task LinkWithGooglePlayGamesAsync(string authCode)
{
try
{
await AuthenticationService.Instance.LinkWithGooglePlayGamesAsync(authCode);
Debug.Log("Link is successful.");
}
catch (AuthenticationException ex) when (ex.ErrorCode == AuthenticationErrorCodes.AccountAlreadyLinked)
{
// Prompt the player with an error message.
Debug.LogWarning("This user is already linked with another account. Log in instead.");
}
catch (AuthenticationException ex)
{
// Compare error code to AuthenticationErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
catch (RequestFailedException ex)
{
// Compare error code to CommonErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
}
#endif
To test this, add this method to the OnClick() event of a UI button.
When you build and run on your Android phone you can see the interface and Google Play Games authentication flow in action. Check the Unity console for the verification messages.
Uploading your apk for distribution
When you upload your apk on the Google Play Console, your signing certificate will change and the sign-in will not work anymore with the development fingerprint.
Go to Test and Release > Setup > App signing, get the new SHA-1 certificate fingerprint, and paste it in the authentication settings of your project:
Check out the next article on how to set up Apple Games Center login.










































