Integrating Firebase Analytics
Understanding player progression and identifying difficulty spikes is easier when you track custom events. Firebase Analytics provides this functionality for Unity, but initialization requires properly configuring your project files, managing asynchronous tasks, and addressing privacy consent.
Configuration Setup
First, import the SDK into your project. You can either import the
Before writing any code, the SDK needs to know which Firebase project to communicate with. You must download the configuration files from the Firebase Console and place them anywhere inside your Unity
For Android, download
For iOS, download
Unity parses these files during the build process to inject the necessary application IDs into your app's manifest and plist.
FirebaseAnalytics.unitypackage from the official Firebase archive, or install it via the Unity Package Manager using the provided .tgz file. Do not mix these two installation methods in the same project. Firebase recommends using one installation method consistently to avoid package and dependency conflicts.Before writing any code, the SDK needs to know which Firebase project to communicate with. You must download the configuration files from the Firebase Console and place them anywhere inside your Unity
Assets folder.For Android, download
google-services.json.For iOS, download
GoogleService-Info.plist.Unity parses these files during the build process to inject the necessary application IDs into your app's manifest and plist.
Dependency Checking and Threading
On Android, the Firebase SDK requires compatible Google Play Services on the device. The official documentation recommends checking and fixing these dependencies before enabling analytics.
Additionally, async task continuations in the Firebase SDK may execute away from Unity's main thread. If you intend to update Unity UI or interact with GameObjects after initialization, you must route that logic back to the main thread. Using
Additionally, async task continuations in the Firebase SDK may execute away from Unity's main thread. If you intend to update Unity UI or interact with GameObjects after initialization, you must route that logic back to the main thread. Using
ContinueWithOnMainThread from the Firebase.Extensions namespace handles this safely for you.Consent-Aware Initialization
Firebase Analytics will begin collecting data as soon as it initializes. Depending on your region and target audience, you may need to delay data collection until the user provides explicit consent.
The most robust way to handle this is to disable automatic collection at the platform configuration level (by adding
The most robust way to handle this is to disable automatic collection at the platform configuration level (by adding
<meta-data android:name="firebase_analytics_collection_enabled" android:value="false" /> to your AndroidManifest and FIREBASE_ANALYTICS_COLLECTION_ENABLED=NO to your iOS Info.plist). You can then manually re-enable it in your script only after confirming the user's consent state:csharp
using Firebase;
using Firebase.Analytics;
using Firebase.Extensions;
using UnityEngine;
public class AnalyticsInitializer : MonoBehaviour {
void Start() {
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
if (task.Result == DependencyStatus.Available) {
// Determine user consent based on your app's consent flow
bool userHasConsented = CheckUserConsent();
if (userHasConsented) {
FirebaseAnalytics.SetAnalyticsCollectionEnabled(true);
Debug.Log("Analytics enabled with consent.");
} else {
Debug.Log("Analytics disabled pending consent.");
}
} else {
Debug.LogError("Could not resolve Firebase dependencies: " + task.Result);
}
});
}
private bool CheckUserConsent() {
// REPLACE THIS with your actual consent logic (e.g., UMP SDK or PlayerPrefs)
return false; // Placeholder implementation
}
}Standard vs Custom Events
Firebase Analytics offers predefined events (like
EventLevelUp or EventTutorialBegin). It is recommended to use these standard events whenever they fit your use case, as they unlock richer reporting features and specialized insights within the Firebase Analytics dashboard. If your tracking needs fall outside the predefined scope, you can log custom events.Logging Events with Parameters
When logging events, grouping related data under a single event name makes your dashboard cleaner. Instead of creating distinct events like
level_1_finished and level_2_finished, you can log a single level_complete event and attach the level ID as a parameter.csharp
using Firebase.Analytics;
using UnityEngine;
public class AnalyticsManager : MonoBehaviour {
public void LogLevelComplete(int levelId, int score) {
Parameter[] parameters = {
new Parameter("level_id", levelId),
new Parameter("final_score", score)
};
FirebaseAnalytics.LogEvent("level_complete", parameters);
Debug.Log($"Logged level_complete for Level {levelId}");
}
}Verifying Events with DebugView
Events logged by the SDK are batched and uploaded periodically to save battery, meaning they can take around one hour to appear in the standard Firebase dashboard. To validate your implementation efficiently during development, use Firebase DebugView for near-real-time validation.
For Android devices connected via USB, you can enable DebugView by running the following ADB command in your terminal:
For Android devices connected via USB, you can enable DebugView by running the following ADB command in your terminal:
tipWatch the DebugView tab in your Firebase Console. Your logged events will stream in almost instantly. To disable it later, run: adb shell setprop debug.firebase.analytics.app .none
bash
adb shell setprop debug.firebase.analytics.app com.yourcompany.yourgameFrequently Asked Questions
Why are my events not showing up in the Firebase Console?
Standard reports are delayed by batching. Use DebugView (as explained above) to verify your events during development.
Why did adding Firebase break my Android build?
Adding Firebase introduces its own set of Google Play Services dependencies, which frequently conflict with other SDKs (like AdMob). Use the External Dependency Manager for Unity (EDM4U) to resolve these. For detailed solutions, see our guide on Common Unity Android Build Errors.
Why are Firebase callbacks throwing errors?
Async task continuations in the Firebase SDK may execute away from Unity's main thread. If you try to update a UI Text component or instantiate a GameObject inside the callback without using
Standard reports are delayed by batching. Use DebugView (as explained above) to verify your events during development.
Why did adding Firebase break my Android build?
Adding Firebase introduces its own set of Google Play Services dependencies, which frequently conflict with other SDKs (like AdMob). Use the External Dependency Manager for Unity (EDM4U) to resolve these. For detailed solutions, see our guide on Common Unity Android Build Errors.
Why are Firebase callbacks throwing errors?
Async task continuations in the Firebase SDK may execute away from Unity's main thread. If you try to update a UI Text component or instantiate a GameObject inside the callback without using
ContinueWithOnMainThread, Unity will throw cross-thread exceptions or behave unpredictably.