Lesson 10: Analytics & User Tracking

Welcome back! Now that you've implemented monetization systems, it's time to understand how players interact with your game. Analytics and user tracking provide the insights you need to make data-driven decisions, optimize player experience, and improve your game's performance. In this lesson, you'll learn how to integrate analytics platforms, track key metrics, and implement A/B testing to continuously improve your mobile puzzle game.

What You'll Learn

  • Understand the importance of analytics in mobile game development
  • Integrate Unity Analytics and Firebase Analytics
  • Track key player behavior metrics and events
  • Implement custom event tracking for game-specific actions
  • Set up A/B testing for game features
  • Analyze data to make informed decisions
  • Create dashboards and reports for key metrics

Prerequisites

  • Unity 2022.3 LTS or newer
  • Completed Lesson 9: In-App Purchases & Monetization
  • Basic understanding of data analysis concepts
  • Unity Analytics package (we'll install it in this lesson)
  • Firebase account (optional, for advanced analytics)

Why Analytics Matter

Analytics transform guesswork into informed decision-making. The most successful mobile games use data to:

  • Understand player behavior - See how players actually interact with your game
  • Identify pain points - Discover where players struggle or drop off
  • Optimize monetization - Test different pricing and placement strategies
  • Improve retention - Understand what keeps players coming back
  • Guide development - Make data-driven decisions about new features

Without analytics, you're flying blind. With proper tracking, every decision can be backed by real player data.

Step 1: Setting Up Unity Analytics

Unity Analytics is a powerful, free analytics solution that's easy to integrate and provides comprehensive insights into player behavior.

Installing Unity Analytics

  1. Open Package Manager:

    • Go to Window > Package Manager
    • Click the "+" button in the top-left
    • Select "Add package by name"
  2. Install Analytics Packages:

    • Enter: com.unity.analytics
    • Click "Add"
    • Wait for installation to complete
    • Also install: com.unity.cloud.build (for cloud services)
  3. Enable Analytics in Project Settings:

    • Go to Edit > Project Settings
    • Navigate to "Services" section
    • Sign in with your Unity ID
    • Enable "Unity Analytics"
    • Create a new project or link to existing project

Configuring Analytics

  1. Set Up Project ID:

    • In Project Settings > Services
    • Note your Project ID (you'll need this for dashboard access)
    • Enable "Cloud Diagnostics" for crash reporting
  2. Configure Build Settings:

    • Go to File > Build Settings
    • Ensure your target platform is selected
    • Analytics works automatically in builds (not in Editor)
  3. Test Analytics Connection:

    • Build and run your game on a device
    • Play through some levels
    • Check Unity Analytics dashboard (analytics.cloud.unity3d.com)
    • Verify events are being received

Pro Tip: Unity Analytics has a 24-hour delay for data to appear in the dashboard. Use the real-time debugger during development for immediate feedback.

Step 2: Tracking Key Player Events

Now that analytics is set up, let's implement tracking for the most important player actions in your puzzle game.

Basic Event Tracking

Create a new script called AnalyticsManager.cs:

using UnityEngine;
using UnityEngine.Analytics;

public class AnalyticsManager : MonoBehaviour
{
    public static AnalyticsManager Instance;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    // Track level start
    public void TrackLevelStart(int levelNumber)
    {
        Analytics.CustomEvent("level_start", new System.Collections.Generic.Dictionary<string, object>
        {
            { "level_number", levelNumber },
            { "timestamp", System.DateTime.Now.ToString() }
        });
    }

    // Track level completion
    public void TrackLevelComplete(int levelNumber, int movesUsed, float timeSpent)
    {
        Analytics.CustomEvent("level_complete", new System.Collections.Generic.Dictionary<string, object>
        {
            { "level_number", levelNumber },
            { "moves_used", movesUsed },
            { "time_spent", timeSpent },
            { "stars_earned", CalculateStars(movesUsed, timeSpent) }
        });
    }

    // Track level failure
    public void TrackLevelFail(int levelNumber, string failureReason)
    {
        Analytics.CustomEvent("level_fail", new System.Collections.Generic.Dictionary<string, object>
        {
            { "level_number", levelNumber },
            { "failure_reason", failureReason },
            { "attempt_number", GetAttemptNumber(levelNumber) }
        });
    }

    // Track purchase events
    public void TrackPurchase(string productId, decimal price, string currency)
    {
        Analytics.Transaction(productId, price, currency);
        Analytics.CustomEvent("purchase_made", new System.Collections.Generic.Dictionary<string, object>
        {
            { "product_id", productId },
            { "price", price },
            { "currency", currency }
        });
    }

    // Track ad views
    public void TrackAdView(string adType, bool rewarded)
    {
        Analytics.CustomEvent("ad_viewed", new System.Collections.Generic.Dictionary<string, object>
        {
            { "ad_type", adType },
            { "rewarded", rewarded },
            { "level_context", GetCurrentLevel() }
        });
    }

    // Helper methods
    private int CalculateStars(int moves, float time)
    {
        // Your star calculation logic
        if (moves <= GetParMoves() && time <= GetParTime()) return 3;
        if (moves <= GetParMoves() * 1.5f) return 2;
        return 1;
    }

    private int GetAttemptNumber(int level)
    {
        // Track attempt number per level
        string key = "level_" + level + "_attempts";
        int attempts = PlayerPrefs.GetInt(key, 0) + 1;
        PlayerPrefs.SetInt(key, attempts);
        return attempts;
    }

    private int GetCurrentLevel()
    {
        // Get current level from your game manager
        return GameManager.Instance?.CurrentLevel ?? 0;
    }

    private int GetParMoves() { return 10; } // Your par logic
    private float GetParTime() { return 60f; } // Your par logic
}

Integrating Tracking into Game Flow

Update your existing game scripts to call analytics events:

// In your LevelManager or GameManager
public class LevelManager : MonoBehaviour
{
    void Start()
    {
        int currentLevel = GetCurrentLevel();
        AnalyticsManager.Instance.TrackLevelStart(currentLevel);
    }

    public void OnLevelComplete()
    {
        int moves = GetMovesUsed();
        float time = GetTimeSpent();
        AnalyticsManager.Instance.TrackLevelComplete(GetCurrentLevel(), moves, time);
    }

    public void OnLevelFailed(string reason)
    {
        AnalyticsManager.Instance.TrackLevelFail(GetCurrentLevel(), reason);
    }
}

Step 3: Setting Up Firebase Analytics (Advanced)

Firebase Analytics provides more advanced features and better integration with other Firebase services. It's especially useful if you plan to use Firebase for other features like cloud messaging or remote config.

Installing Firebase

  1. Download Firebase Unity SDK:

    • Visit firebase.google.com/download/unity
    • Download the latest Firebase Unity SDK
    • Import FirebaseAnalytics.unitypackage into your project
  2. Set Up Firebase Project:

    • Go to Firebase Console (console.firebase.google.com)
    • Create a new project or use existing
    • Add your Android/iOS app to the project
    • Download google-services.json (Android) or GoogleService-Info.plist (iOS)
  3. Configure Firebase:

    • Place configuration files in appropriate folders
    • Initialize Firebase in your game startup:
using Firebase;
using Firebase.Analytics;

public class FirebaseManager : MonoBehaviour
{
    void Start()
    {
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
            if (task.Result == DependencyStatus.Available)
            {
                FirebaseAnalytics.SetAnalyticsCollectionEnabled(true);
                Debug.Log("Firebase Analytics initialized");
            }
            else
            {
                Debug.LogError("Firebase dependencies not available");
            }
        });
    }

    public void LogEvent(string eventName, Dictionary<string, object> parameters)
    {
        FirebaseAnalytics.LogEvent(eventName, parameters);
    }
}

Step 4: Key Metrics to Track

Not all events are created equal. Focus on tracking metrics that directly impact your game's success:

Retention Metrics

  • Day 1 Retention - Percentage of players who return the day after first play
  • Day 7 Retention - Percentage of players who return after a week
  • Day 30 Retention - Long-term player engagement

Engagement Metrics

  • Session Length - Average time players spend per session
  • Sessions Per Day - How often players return
  • Levels Completed - Progression through your game
  • Time to First Purchase - How long before players monetize

Monetization Metrics

  • Conversion Rate - Percentage of players who make purchases
  • Average Revenue Per User (ARPU) - Total revenue divided by total users
  • Lifetime Value (LTV) - Total revenue from a player over their lifetime
  • Purchase Frequency - How often players make purchases

Progression Metrics

  • Level Completion Rate - Percentage of players who complete each level
  • Average Attempts Per Level - Difficulty indicator
  • Power-up Usage - Which power-ups players use most
  • Hint Usage - How often players need help

Step 5: Implementing A/B Testing

A/B testing allows you to test different versions of features to see which performs better. This is crucial for optimizing monetization, difficulty, and player experience.

Setting Up A/B Tests

  1. Define Your Test Hypothesis:

    • Example: "Showing a purchase prompt after level 5 will increase conversion by 20%"
    • Example: "Reducing difficulty by 10% will improve retention"
  2. Create Test Variants:

    • Variant A: Control (current version)
    • Variant B: Test (new version)
  3. Implement Test Logic:

public class ABTestManager : MonoBehaviour
{
    private string currentVariant;

    void Start()
    {
        // Assign player to variant (50/50 split)
        currentVariant = PlayerPrefs.GetString("ab_variant", "");
        if (string.IsNullOrEmpty(currentVariant))
        {
            currentVariant = UnityEngine.Random.Range(0, 2) == 0 ? "A" : "B";
            PlayerPrefs.SetString("ab_variant", currentVariant);
        }

        ApplyVariant();
    }

    void ApplyVariant()
    {
        if (currentVariant == "B")
        {
            // Apply test variant changes
            ShowPurchasePromptAfterLevel(5);
            AdjustDifficulty(-0.1f);
        }
        else
        {
            // Control variant (no changes)
        }

        // Track which variant player is in
        AnalyticsManager.Instance.TrackEvent("ab_test_assigned", 
            new Dictionary<string, object> { { "variant", currentVariant } });
    }
}

Analyzing A/B Test Results

  1. Set Test Duration:

    • Run tests for at least 1-2 weeks
    • Ensure statistical significance (enough sample size)
  2. Compare Key Metrics:

    • Conversion rates between variants
    • Retention rates
    • Revenue per user
    • Player satisfaction (if tracked)
  3. Make Data-Driven Decisions:

    • If variant B performs better, roll it out to all players
    • If no significant difference, keep current version
    • Document learnings for future tests

Step 6: Creating Analytics Dashboards

Organize your analytics data into easy-to-read dashboards that help you make quick decisions.

Key Dashboard Views

  1. Daily Active Users (DAU) Dashboard:

    • Track daily player count
    • Identify trends and spikes
    • Compare week-over-week growth
  2. Revenue Dashboard:

    • Daily revenue
    • Revenue by source (IAP, ads)
    • Top-selling items
    • Revenue trends
  3. Retention Dashboard:

    • Day 1, 7, 30 retention rates
    • Cohort analysis
    • Churn prediction
  4. Level Progression Dashboard:

    • Level completion rates
    • Stuck points (where players fail most)
    • Average attempts per level
    • Time spent per level

Building Custom Reports

Most analytics platforms allow you to create custom reports. Focus on:

  • Funnel Analysis - Track player journey from install to purchase
  • Cohort Analysis - Compare player groups by install date
  • Event Flows - See common player action sequences
  • Geographic Analysis - Understand regional differences

Step 7: Privacy and Compliance

With analytics comes responsibility. Ensure you're compliant with privacy regulations:

GDPR Compliance (Europe)

  • Get Consent - Show privacy policy and get user consent before tracking
  • Allow Opt-Out - Provide option to disable analytics
  • Data Minimization - Only collect necessary data
  • Right to Deletion - Allow users to request data deletion

CCPA Compliance (California)

  • Privacy Notice - Inform users about data collection
  • Opt-Out Rights - Allow users to opt out of data sale
  • Data Access - Provide users access to their data

Implementation Example

public class PrivacyManager : MonoBehaviour
{
    public GameObject consentPanel;

    void Start()
    {
        if (!HasUserConsented())
        {
            ShowConsentPanel();
        }
        else
        {
            EnableAnalytics();
        }
    }

    public void OnConsentGiven()
    {
        PlayerPrefs.SetInt("analytics_consent", 1);
        EnableAnalytics();
        consentPanel.SetActive(false);
    }

    public void OnConsentDenied()
    {
        PlayerPrefs.SetInt("analytics_consent", 0);
        DisableAnalytics();
        consentPanel.SetActive(false);
    }

    private void EnableAnalytics()
    {
        AnalyticsManager.Instance.enabled = true;
    }

    private void DisableAnalytics()
    {
        AnalyticsManager.Instance.enabled = false;
    }

    private bool HasUserConsented()
    {
        return PlayerPrefs.GetInt("analytics_consent", 0) == 1;
    }
}

Mini Challenge: Implement Analytics Tracking

Your challenge is to implement comprehensive analytics tracking in your mobile puzzle game:

  1. Set up Unity Analytics in your project
  2. Create AnalyticsManager script with key event tracking
  3. Track at least 5 different events:
    • Level start
    • Level complete
    • Level fail
    • Purchase made
    • Ad viewed
  4. Integrate tracking into your existing game code
  5. Test analytics by building and running on a device
  6. Verify events appear in Unity Analytics dashboard

Success Criteria:

  • Analytics events fire correctly
  • Data appears in dashboard (may take 24 hours)
  • No performance impact from tracking
  • Privacy consent implemented

Pro Tips:

  • Start with basic events, add more as needed
  • Don't over-track - focus on actionable metrics
  • Test in development builds first
  • Use debug logs to verify events fire correctly

Common Mistakes to Avoid

Over-Tracking

Problem: Tracking too many events creates noise and makes analysis difficult.

Solution: Focus on events that directly impact key metrics. Start with 10-15 core events and expand only when needed.

Not Testing Analytics

Problem: Assuming analytics "just works" without testing leads to missing data.

Solution: Always test analytics in development builds. Use debug logs and real-time dashboards to verify events fire correctly.

Ignoring Privacy

Problem: Not getting user consent or not complying with regulations leads to legal issues.

Solution: Implement consent flows from day one. Stay updated on privacy regulations in your target markets.

Not Acting on Data

Problem: Collecting analytics but not using it to make decisions defeats the purpose.

Solution: Schedule regular data review sessions. Make analytics-driven decisions about features, difficulty, and monetization.

Troubleshooting

Analytics Not Working

Symptoms: Events not appearing in dashboard after 24+ hours.

Solutions:

  • Verify Unity Analytics is enabled in Project Settings
  • Check that you're testing on a device (not Editor)
  • Ensure internet connection is available
  • Check Unity Analytics dashboard for any error messages
  • Verify Project ID matches in settings and dashboard

Performance Impact

Symptoms: Game feels slower after adding analytics.

Solutions:

  • Batch events instead of sending individually
  • Use async/await for analytics calls
  • Limit event frequency (don't track every frame)
  • Consider using a queue system for events

Privacy Compliance Issues

Symptoms: App rejected from stores or user complaints.

Solutions:

  • Implement proper consent flows
  • Update privacy policy with analytics disclosure
  • Provide opt-out mechanism
  • Test consent flows thoroughly before submission

Next Steps

Congratulations! You've implemented comprehensive analytics tracking in your mobile puzzle game. You can now:

  • Make data-driven decisions about game design
  • Optimize monetization based on real player behavior
  • Improve retention by understanding player drop-off points
  • Test new features with A/B testing before full rollout

In the next lesson, you'll learn about App Store Optimization - how to make your game discoverable and attractive to potential players in app stores. You'll create compelling store listings, optimize keywords, and design screenshots that convert browsers into players.

Bookmark this lesson - Analytics is an ongoing process. You'll refer back to these concepts as you continue to optimize your game.

Share your analytics implementation with the community and get feedback on your tracking strategy.

For more advanced analytics techniques, check out our Game Analytics Guide or explore Firebase Documentation for additional features.


Analytics is a powerful tool, but remember: data tells you what's happening, not why. Always combine analytics insights with player feedback and your own game design intuition to make the best decisions.