Integrating Firebase With Unity

Integrating Firebase With Unity

Somehow, whenever I try to integrate my Unity game with any mobile integration, be it analytics, messaging, leaderboards, whatever, it will always fail to build. And seeing all your hard work potentially going up in smokes because of some mobile plugins refusing to play along with each other truly, truly sucks. And I wouldn't wish that upon my worst enemies. 

Well, maybe not, maybe I wish they'd experience that, but whatever.

So, it is imperative that you start any of your Unity mobile game project with all of the boring parts covered very early on. 

And unfortunately, they're not exactly optional, because for example if you're promoting your app via Adwords, you need Firebase Analytics installed in your iOS builds or Google's Universal App Campaign AI won't be able to track your installs, and hence you will not be able to run any campaign in the first place, unless you want to build a landing page first and promote it the classic way (Search campaign and stuff).

This tutorial will start from an empty Unity 2D project using Unity 2018.3.0f2.

So, enough babbling, let's go!

0. New Project

Nothing fancy here. Just open Unity and create a new project.

0b. Install Github for Unity

Yep, install Github for Unity first. It's a life saver.

 You can follow this Github for Unity Tutorial if you want.

1. Add Firebase to Unity project

To be honest, Google's docs are pretty good and you should have no problems if you follow the steps to a T. 

https://firebase.google.com/docs/unity/setup

Adding the Analytics package should be enough for now.

Be sure to do both for Android and iOS project.

By the end of this step you should have installed the Firebase-Unity SDK and have google-services.json and GoogleService-Info.plist inside your Unity project.

2. Add code to record events in Firebase

Now that you've successfully added Firebase, now let's make sure they actually work. This step is also written in Firebase's docs, but I'll just write them down here for more clarity.

Inside your initial scene, add an empty GameObject.

Create a C# script named FirebaseScript

Replace the placeholder script with the following code

using Firebase;

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

 

public class FirebaseScript : MonoBehaviour

{

 

    FirebaseApp _app;

    private bool _firebaseExists = false;

 

    // Start is called before the first frame update

    void Start()

    {

 

        Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {

            var dependencyStatus = task.Result;

            if (dependencyStatus == Firebase.DependencyStatus.Available)

            {

                // Create and hold a reference to your FirebaseApp, i.e.

                _app = Firebase.FirebaseApp.DefaultInstance;

                // where app is a Firebase.FirebaseApp property of your application class.

 

                // Set a flag here indicating that Firebase is ready to use by your

                // application.

                _firebaseExists = true;

 

                Firebase.Analytics.FirebaseAnalytics

                  .LogEvent(Firebase.Analytics.FirebaseAnalytics.EventEarnVirtualCurrency);

 

            }

            else

            {

                UnityEngine.Debug.LogError(System.String.Format(

                  "Could not resolve all Firebase dependencies: {0}", dependencyStatus));

                // Firebase Unity SDK is not safe to use here.

            }

        });

 

    }

 

    // Update is called once per frame

    void Update()

    {

 
    }

}

 

Lastly, attach the FirebaseScript.cs to the GameObject.

What happens is that FirebaseScript will initialize Firebase and log a EventEarnVirtualCurrency event each time this scene is started up.

Now that we're done, let's actually test our integration.

3. Build for Android and test it

Go to File > Build Settings. Click Android and Switch Platform.

Open Player Settings

Set keystore 

Set your package name

Build

There's a chance that your build may fail. If so, simply close Unity, pray to your god of choice and open it again. It should work.

Now copy that APK file into your Android device and install your app.

4. Firebase DebugView

Yay, it works! However, Firebase only updates the data hourly or daily or so. Ain't nobody got the time for that, so let's use Firebase's Debug View instead.

First, we'll need to enable Firebase's Debug mode on your Android device first.

Open command prompt and go to your Android SDK folder and open the platform-tools folder. For example, my Android SDK folder is at F:\dev\androidsdk\platform-tools .

Next, run this command.

adb shell setprop debug.firebase.analytics.app <package_name>

(replace <package_name> with your app's package name)

However, if you're a hotshot like myself and have two Android devices connected to your PC, then you'll get an error saying something to the effect of "I don't know which device should I send this command to".

If so, then run this command first to get a list of devices attached to your PC.

adb devices

..Then guess which one is your device and run this modified adb command instead that will direct the command to that specific device.

adb -s <device_id> shell setprop debug.firebase.analytics.app <package_name>

(ref: https://stackoverflow.com/questions/14654718/how-to-use-adb-shell-when-multiple-devices-are-connected-fails-with-error-mor)

Alright, now that debug mode is on, let's scoot over to Firebase's Debug View.

Simply open Firebase console and go Analytics > DebugView

The events should be empty.

Now, run your app again.

Now, wait a bit. Hurray! Your events should now be logged inside Firebase.

 

Remember to disable the debug mode again by running this command:

adb shell setprop debug.firebase.analytics.app .none.

Sample project available at Github

https://github.com/purrmiaw/unitymobilebase