Firebase Tutorial: Adding Google Play Games Auth to Unity

Firebase Tutorial: Adding Google Play Games Auth to Unity

Welcome to the firebase tutorial for how
to add Google Play Games Auth to your Unity game. This tutorial will cover
everything you need to do to get Firebase Auth working with the Google
Play Games identity provider in Unity. We’ll begin with how to get a working
Android build then we’ll cover how to add Firebase to your game, after that
we’ll cover how to add Google Play Game Services to your game, and finally we’ll
cover how to use the Firebase Play Games Identity provider to authenticate your
users to Firebase. This Firebase tutorial will pick up where the main menu
tutorial left off, mostly because it’s the easiest place to add a button. You
can also use your own Unity game instead. To start it let’s try to build an
Android version of the game. Open the build settings and click on Android to
highlight it. Now click switch platform. You’ll notice that the Unity cube is now
beside the Android platform indicating this is the active platform. Now if you
were to click build and select a name for your build and click Save, if you
haven’t set up your Android build you’ll get this error it’s because there’s no
Android package name set up yet. So let’s set that up in the build settings dialog.
Click on player settings. This will open player settings in the inspector in the
main Unity window. Under settings for Android, click on ‘other settings’ to open
the section if it isn’t already open. There are a lot of settings, but for now
we just need to set one of them. In the identification section we need to set
the package name to something other than this invalid default. For this example we
will call the company ‘my company’ and the product ‘firebase tutorial’. If you’re
working on a real game instead of this tutorial then you would of course put in
your real company name and the name of your game instead. We’re going to
need this package need for further setup so just copy and paste it somewhere
convenient. I’m going to use TextEdit. Now we can build again, and this time the
build succeeds – but this build isn’t signed and if you want to use firebase
auth, your build must be signed – even during development. So let’s sign it.
First be sure you are building in release mode, and that means making sure
that the Development Build check box is not checked, and then make sure that the
player settings are still showing in the inspector or click on them again. Close
the other settings and open publishing settings. We need to create a new key
store. Check the ‘create a new key store’ box, then click on ‘browse key store’ to
select a name for the key store. I chose ‘release’ as the name for my key store since
this is for a release build. I stored it in the top-level ‘Firebase Tutorial’
folder. You can name your key store whatever you want and store it wherever
suits you. Just remember where you put it because we’re going to need to find it
again. Then click ‘Save’. You will now see the name of the key store beside the
‘browse keystore’ button. Create a new password for your new keystore and
confirm it. Now click on the key alias and click on ‘create a new key’. This will
open the create a new key dialog. Fill in the information. I called my key
‘releasekey’. You can name yours whatever you like. Then click ‘Create Key’. Make sure that the alias is the key you just created and
the password is entered as well. Now when you build, your apk will be signed. We
will need the signing certificate fingerprint for later setup and now is a
good time to get it. Open a terminal and navigate to the directory containing
your keystore then use the keytool command as shown here – specifying the
name of your key (in my case releasekey) and the name of your key store (in my
case ‘release.keystore’) and then press enter. You will be asked for the keystore
password. Enter it, and then you’ll see a record of the release key information
including certificate fingerprints with md5, sha-1, and sha-256 values.
Copy the sha-1 value and paste it somewhere convenient again. We will
need these values for future setup. That completes section one. For
section two we’re going to be adding Firebase to Unity, so go to firebase Here you can read a bit more about Firebase if you want. For now click
on ‘Get Started’ to go to the firebase console.
Then click on ‘Add Project’ to add a new Firebase project.
Fill in the name of your project and choose a project ID. Finally click ‘Create
Project’. Firebase will create a project for you. Now you need to add an app to
your project. Click on ‘Add Firebase to your Android app’. Here is where we need
the information from before. Copy from your convenient location into the dialog,
then click ‘Register App’. Once your app is registered you will want to download the
Google services JSON file, but ignore the rest of the instructions because
they are for Android studio, and we’re using Unity. Now click on ‘Unity’ to open
another page that has more information on Unity, and also the SDK download. On
this page just click the ‘Download the SDK’ button to get the SDK. Once it’s
finished downloading, you’re done with this page and you can close it. (Or of
course you can leave it open to read more later if you like).
So, we already registered the app in step one, and we got the config file and
downloaded the SDK two which are steps two and three, so you’re also done with
this page and you can go ahead and close that too. So this is the page you will
see after your app is registered. Now we need to move the Google services JSON
file that we downloaded for step two and put it in your top-level unity project
folder. Also unzip the firebase unity SDK you downloaded for step three by double
clicking it. I put mine on my desktop for convenience. Now we need to import it
into unity. In unity pick assets->import package->custom package, find your
unzipped firebase Unity SDK folder, and pick ‘FirebaseAuth.unitypackage’. Then
click open. Leave everything selected and click on
‘Import’. The FirebaseAuth.unitypackage will be imported. The resolver should
also run automatically. Now before you do anything else, it’s important to note
that the resolver can sometimes be a bit finicky. It’s very important to let
it finish resolving before you try to do anything else in Unity or it may fail
and leave things in a weird state. That’s the end of section two. Now let’s
move on to Section 3 configuring Google Play game services. If you don’t already
have a Google Play Developer Account, you need to sign up and pay the
registration fee before continuing to the next step.
From the Google Play console, click on ‘Game services’. Click on ‘Add new game ‘. We already registered the game project in the Firebase console, so click on ‘I
already use Google APIs in my game’. Then click on your game to select it. I
should just note here if you’re using your own game and you can’t see the
Firebase console project, then the issue is often permissions. You must be an
owner of the Firebase project before you can link it in Play Games. If you are
an owner and you still can’t see it, it’s possible that it’s already linked to a
different play games project – possibly by a different owner. A firebase project may
be linked to a maximum of one play games project. So hopefully that will help you.
Once you’ve selected your game also select the type of game. Since this
is just a tutorial, I’ll pick ‘casual’. It doesn’t really matter. If you’re writing
a real game, you should of course pick the category that best describes your
game. Click continue. Now you’ve registered your game with Google Play.
Scroll down. You need to make sure that the Google Play Game Services and
Google Play Game Management APIs are turned on for your API console project.
If they’re not already on, click on the ‘Turn APIs back on’ button. After
they’re turned back on, it should look like this. So your projects are now
linked, but you still need to add the app. Click on linked apps. Click on Android.
You’ll need your package name again. Copy and paste it. Click on ‘Save and
continue’. Linking apps is actually linking the
client IDs. This is your Android client ID because it’s an Android app.
You don’t need this Android client ID for any other configuration. If you
try to use it you’re going to get errors. So just click ‘Back to the list’.
Now whenever you make a Firebase project, Google automatically creates a web
client ID for it. We will need this web client ID for further configuration
later. Again *not* the Android one. I can’t stress that enough.
Now we’re going to link the web client ID to Play Games as well. Click ‘Link
another app’, then click on Web. Don’t worry, we’re not actually creating a web app; We
just need to link the web client ID. If this is for a tutorial only, then you
can fill in some dummy URL here. But if it’s for an app that you plan to
publish, then it needs to be a real URL, or and won’t be able to publish it.
I’m not going to publish this tutorial game, so I’m just going to use a dummy
URL. Then click on ‘Save and continue’. Click on ‘Show apps and select’. This
is the automatically created web client ID. This is the one that we want. Click it
to select it. Then click select. This is your web client ID. This is the one
you’ll need later for configuration. So let’s go ahead and save that web client
ID to the convenient location. Now we need to pay attention to the middle part
of the ID highlighted in green. This is the thing that we’re going to be
looking for, to try to match it in the next step. Then click on the API console
link so we can get the matching secret. This API console screen can be confusing
if you’re not familiar with it. It’s very important to get the right information,
so make sure that you’re picking the item that says web client, and that the
middle part of the client ID on the right matches what you just saved to
your convenient location. Click on it to see the client secret. We already
have the web client ID in our convenient location. Now copy the matching client
secret and paste it there too. Go back to the Play games console, then
click ‘Continue to next step’. We’re not going to add an event in this tutorial
so just continue to the next step. But we are going to need to add an achievement
though. Click add achievement, fill in your achievement and then click Save. The
reason we need to add an achievement is because otherwise we won’t be able to
see the ‘Get resources’ link. Click on ‘Get resources’, select all the XML and copy it and then click done. Paste it into your convenient
location. We will not be adding a leaderboard for this tutorial. Continue
to the next step. If you want anyone to be able to test your app before it’s
published, they will need to be white listed here before they can use it.
Forgetting to whitelist your testers is a common error. The auth will fail if
they’re not whitelisted. So click ‘Add Testers’. Add your testers, then click Add.
Click ‘Continue to next step’. That concludes the console setup of Play game
services. Now we’ll need to get the Unity Play game services plug-in. It’s on
github follow this link. Click on the releases section. On the most recent
release, click the zip file to download it. Once the download is complete I put
it on my desktop for simplicity again. Double click to unzip it. Go back to
Unity, click on Assets->Import Package->Custom Package. Navigate to the directory
where you unzipped it. Choose current build, and select the Google Play Games plug-in
Unity package. Click open. Keep everything selected, and click import. Wait for
everything to import. This will take a while. The resolver will also run
automatically after a while, and you may get additional informational messages
about obsolete files. You can delete them if you like. You may also get
missing Android SDK packages. Wait for them to be installed too. When the
import is complete, you will see this dialog. Click OK and wait for the package
resolver to finish running. Again, if you don’t, you will likely get weird build
errors. Once the resolver is done running, you will see this dialog. Click OK. Now we
can follow the instructions from the first dialog box. In Unity, click on
Window->Google Play Games->Setup->Android setup. Here’s where we need some of the
stuff we saved. Copy and paste it, and then click ‘Setup’. You should see the
success dialog box. Then just click ‘OK’. Now you should be able to build
successfully. That concludes the setting up the Play Games unity plugin
section. Now we’ll setup Firebase Auth to use Play Games. Go back to the Firebase
console and choose your project. In the authentication section, click ‘Get Started’.
Then click ‘Set up sign-in method’. Click Play Games. Click enable, and fill in the
web client ID and secret. Click Save. You should now see the Play
Games Auth provider enabled. That concludes section 5. Section 6 is the
final section on how to put everything together. Signing a player into Firebase
using the Play Games auth provider is a three step process. Step 1) Sign in to
play games and get a server auth code. Step 2) Make a PlayGamesAuthCredential
from the server auth code. and Step 3) Sign in to Firebase with the PlayGamesAuthCredential.
Since this is a tutorial, we’re going to use a button to
kick off the sign-in procedure for simplicity. For real apps you should
silently sign-in at the beginning of the game instead if you can, and only show
the sign-in button if the silent sign-in fails. So building on top of the ‘Creating
a Main Menu’ tutorial I mentioned in section 1, we’re going to duplicate the
start button. Move the duplicate above the original start button. Call it
sign-in button, and change the text to be ‘Sign In’. The duplicate also has the same
handlers as the original, so remove the old onclick handler. Also remove the ‘load
scene on click’ script because we don’t need that. In the inspector, click ‘Add
Component, then ‘New Script’. Call it SignInOnClick. Then click ‘Create’ and
add. Move the script into your scripts folder. Double-click it to open. Modify
the script to look like this. There’s a Start function which initializes the
play games configuration and activates it. Then there’s a SignInWithPlayGames
function which initializes firebase auth, signs into play games, gets the server
auth code, creates a credential from the server auth code, and finally signs into
Firebase using the credential. So once your code looks like this, save it and go
back to Unity. Click on plus to add an onClick. Drag the script into the ‘none’
object space, and select SignInOnClick->SignInWithPlayGames. Now we can
build it. And finally we can test it. So open a terminal, and navigate to the
builds directory. Attach an Android device or emulator if it’s not already attached.
Install the apk. Clear the log for simplicity. Start the log, and look for
the debug messages we added. On the device, start the Firebase Tutorial app,
and click on Sign In. Once the logs show “User signed in successfully” you can
quit. Congratulations you’re done. Hopefully this tutorial was helpful for you.

22 thoughts on “Firebase Tutorial: Adding Google Play Games Auth to Unity

  1. GetServerAuthCode() keeps returning null.

    Any idea where i might have gone wrong ?

  2. Here's the code, so you don't have to type it out:

    using System.Collections;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using UnityEngine;
    using GooglePlayGames;
    using GooglePlayGames.BasicApi;
    using Firebase.Auth;

    public class SignInOnClick : MonoBehaviour {

    // Use this for initialization
    void Start () {
    // Initialize Play Games Configuration and Activate it.
    PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
    .RequestServerAuthCode(false /*forceRefresh*/)
    PlayGamesPlatform.Activate ();
    Debug.LogFormat ("SignInOnClick: Play Games Configuration initialized");

    public void SignInWithPlayGames () {
    // Initialize Firebase Auth
    Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;

    // Sign In and Get a server auth code.
    UnityEngine.Social.localUser.Authenticate ((bool success) => {
    if (!success) {
    Debug.LogError ("SignInOnClick: Failed to Sign into Play Games Services.");

    string authCode = PlayGamesPlatform.Instance.GetServerAuthCode ();
    if (string.IsNullOrEmpty (authCode)) {
    Debug.LogError ("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
    Debug.LogFormat ("SignInOnClick: Auth code is: {0}", authCode);

    // Use Server Auth Code to make a credential
    Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode);

    // Sign In to Firebase with the credential
    auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
    if (task.IsCanceled) {
    Debug.LogError ("SignInOnClick was canceled.");
    if (task.IsFaulted) {
    Debug.LogError ("SignInOnClick encountered an error: " + task.Exception);

    Firebase.Auth.FirebaseUser newUser = task.Result;
    Debug.LogFormat ("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);

  3. Thank you for the helpful video. It was very clear and concise to follow (still stuck at resolving dependencies though 🙁 ). One suggestion for future is to also include the useful links in the description.

  4. after a whole day try and error this finally work for me. relay helpful.

  5. Thank you so much for the video…..This is really helpful.

  6. Thanks for the video. It was really helpful 🙂

  7. If it's not working for you but you feel you have followed the steps correctly, carefully LOOK through the logs for any errors and google them!

  8. I am stuck in Resolving Android Dependencies. It all started after Unity notify me that some stuff in the package are obsolete and ask me if I want to delete them. So, I clicked 'yes' and now stuck in RAD.

  9. so I'm getting "Failed to get Auth" for some reason.

  10. it is possible to get player gmail address in firebase????

  11. like and subscribe 😀

  12. Hello. Thanks for your tutorial. I have tried everything and still getting this error with the app crashing. Can you help?
    10-28 18:05:51.908: E/Unity(31919): Java class com/google/firebase/auth/FirebaseAuthWebException not found. Please verify the AAR which contains the com/google/firebase/auth/FirebaseAuthWebException class is included in your app.

  13. i successfully play games signed in in my phone but i can't see user in firebase ? what is the problem? if i cant see user, How can i manage the database or high score or coin for the this user?

  14. what could be the cause of the error?

    SignInOnClick: Failed to Sign into Play Games Services.
    <SignInWithPlayGames>c__AnonStorey0:<>m__0(Boolean) (at Assets/Scripts/SignInOnClick.cs:27)
    GooglePlayGames.<Authenticate>c__AnonStorey0:<>m__0(Boolean, String) (at Assets/GooglePlayGames/ISocialPlatform/PlayGamesPlatform.cs:383)
    GooglePlayGames.BasicApi.DummyClient:Authenticate(Action`2, Boolean) (at Assets/GooglePlayGames/BasicApi/DummyClient.cs:50)
    GooglePlayGames.PlayGamesPlatform:Authenticate(Action`2, Boolean) (at Assets/GooglePlayGames/ISocialPlatform/PlayGamesPlatform.cs:414)
    GooglePlayGames.PlayGamesPlatform:Authenticate(Action`1, Boolean) (at Assets/GooglePlayGames/ISocialPlatform/PlayGamesPlatform.cs:383)
    GooglePlayGames.PlayGamesPlatform:Authenticate(Action`1) (at Assets/GooglePlayGames/ISocialPlatform/PlayGamesPlatform.cs:348)
    GooglePlayGames.PlayGamesLocalUser:Authenticate(Action`1) (at Assets/GooglePlayGames/ISocialPlatform/PlayGamesLocalUser.cs:49)
    SignInOnClick:SignInWithPlayGames() (at Assets/Scripts/SignInOnClick.cs:25)

  15. شرح رائع
    انه يعمل
    شكرا حزيلا ^_^

  16. Thank you very much for this tutorial!! Helped me a lot!! One question, how do I hide the sign in button after I authenticate my google account?

  17. Hi, is there any chance you could do a tutorial for the Google Login Auth?

  18. I made all the settings but "Failed to Sign into Play Games Services." see. Can you tell me how to fix it? My error log is this "INVALID_CLIENT_ID"

  19. 5:47 The directory shown in the picture is wrong , the google-services.json file needs to be inside the "Assest" folder of your project !

  20. bool success always return false, and I'm sure my SHA-1 is the same with my App.

  21. Thank you! This was helpful 🙂

  22. Google Play Sign In was work at bluestack but open My game with any android device , sign not work ı dont know why like this ?

Leave a Reply

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