Which analytics options does a Unity game have?

Three common options are Manalens, Unity Analytics and GameAnalytics. Each one is an SDK that you add to the project. The table shows what each vendor documents on its public pages.

The rest of this guide uses the Manalens SDK. The order of the work is the same for any SDK: install, start, send events, set versions, check the data.

Unity analytics options, from each vendor's public documentation and pricing page.
OptionInstallUnity versionPublic price
ManalensUnity Package Manager package, on request during early access. No dependencies.2021.3 or laterFrom $79 a month for up to 10K MAU. No free plan. 7-day trial.
Unity Analytics (Unity Gaming Services)Unity Gaming Services setup. gameStarted, gameRunning and gameEnded are automatic.Not stated on the pages we readFree up to 50,000 active users a month, then from $0.00360 per MAU
GameAnalyticsOpenUPM or a .unitypackage. One GameAnalytics object in the scene, then GameAnalytics.Initialize().2022.3 or laterFree plan with no MAU cap. Paid plans add features.

Sources: Manalens Unity SDK documentation and pricing; Unity Analytics documentation and Unity Gaming Services pricing; GameAnalytics Unity SDK documentation and pricing.

What do I need before I start?

You need four things. Get them before you open the Package Manager.

Never put a Secret key or an API key in a build. Init() refuses them and returns false.

  • Unity 2021.3 or later. The package is plain C# with no native code and no dependencies.
  • The SDK package. During early access, it is available on request from the contact page. The source will be published at launch.
  • The Publishable key of your Manalens project. It starts with mana_pk_. It is safe to ship in a build, because it can send events and cannot read data.
  • Your collector endpoint: the collector URL without /v0/events.

Sources: Manalens Unity SDK documentation.

How do I install the SDK package?

Use the Package Manager. Unity can install a package from a folder on your disk or from a .tgz file, so you do not need a registry. The Unity Manual gives the steps for each case.

  1. Request the Unity SDK from the contact page, and save the package on your computer.
  2. In Unity, open Window, Package Manager, and click the install (+) button in the toolbar.
  3. If you received a folder, select Install package from disk, go to the root of the package folder and open its package.json file.
  4. If you received a .tgz file, select Install package from tarball and open the file. The file dialog recognizes a tarball only when it has the .tgz extension.
  5. Check that Manalens (dev.manalens.sdk) is in the package list.
  6. Optional: import the Basic setup sample from the package. It has a ready AnalyticsBootstrap component.

Sources: Manalens Unity SDK documentation; Unity Manual, Install a UPM package from a local folder and from a local tarball file.

How do I start the SDK?

Call Manalens.Init() once, on the main thread, in the Awake() of a component in your first scene. Init() sends session_start and game_open, with is_first_open and first_open_at. It returns false and logs the reason when an option is wrong. The SDK then stays off.

Unity calls Awake() once in the lifetime of a script instance, and again when the scene loads again. A second Init() call returns false and logs a warning, so the component below checks IsInitialized first.

Enabled = !Application.isEditor turns the SDK off in Play mode. Application.isEditor says whether the game runs inside the Unity Editor. With Enabled set to false, every call does nothing: no events, no files and no stored ID.

C#

using UnityEngine;
using ManalensSdk;

// Add this component to one GameObject in your first scene.
public class AnalyticsBootstrap : MonoBehaviour
{
    void Awake()
    {
        if (Manalens.IsInitialized) return; // the first scene loaded again

        Manalens.SendFailed += (status, dropped) =>
            Debug.LogWarning($"Analytics dropped {dropped} events (HTTP {status})");

        bool started = Manalens.Init(new ManalensOptions
        {
            PublishableKey = "YOUR_PUBLISHABLE_KEY",
            Endpoint = "https://YOUR_COLLECTOR_ENDPOINT", // without /v0/events
            Build = BuildInfo.Build, // the BuildInfo class is in a later section
            Storefront = "steam",
            Enabled = !Application.isEditor,
        });
        if (!started) Debug.LogWarning("Analytics did not start. The log line before this one has the reason.");
        else BuildInfo.ReportUpdate();
    }
}

Sources: Manalens Unity SDK documentation; Unity Scripting API, MonoBehaviour.Awake and Application.isEditor.

How do I send my first events?

Call Track() with a snake_case name and a dictionary of flat properties. Values are strings, numbers, booleans or null. An enum value is sent as its name. The SDK drops lists, dictionaries and objects, and logs a warning. Track() can be called from any thread.

Use the event conventions in the table, so that the Game KPIs board reads your events without setup. Put the level number in a property, not in the event name. Keep all calls in one static class, as below, so that every name is written in one place.

The first events for a Unity game, their properties and who sends them.
EventPropertiesSent by
game_openis_first_open, first_open_atThe SDK, each launch
session_startnoneThe SDK
session_endduration_sThe SDK
level_startlevel, attemptYour code
level_complete, level_faillevel, attempt, scoreYour code
resourceflow (source or sink), currency, amount, itemYour code
purchaseamount_cents, currency, storeYour code
errorseverity, message, error_type, handled, fingerprintThe SDK and TrackError()
app_unclean_exitprevious_session_id, previous_buildThe SDK, at the next launch after a crash
game_updatedprevious_version, previous_buildYour code

C#

using System;
using System.Collections.Generic;
using ManalensSdk;

public static class GameEvents
{
    public static void LevelStart(int level, int attempt) =>
        Manalens.Track("level_start", new Dictionary<string, object> { ["level"] = level, ["attempt"] = attempt });

    public static void LevelComplete(int level, int attempt, int score) =>
        Manalens.Track("level_complete", new Dictionary<string, object> { ["level"] = level, ["attempt"] = attempt, ["score"] = score });

    public static void LevelFail(int level, int attempt, int score) =>
        Manalens.Track("level_fail", new Dictionary<string, object> { ["level"] = level, ["attempt"] = attempt, ["score"] = score });

    public static void Spend(string currency, int amount, string item) =>
        Manalens.Track("resource", new Dictionary<string, object> { ["flow"] = "sink", ["currency"] = currency, ["amount"] = amount, ["item"] = item });

    // A caught exception: the SDK sends its type, message, stack and place in the code.
    public static void Caught(Exception exception) => Manalens.TrackError(exception);
}

Sources: Manalens Unity SDK and app events documentation.

How are sessions counted?

The SDK counts them, and you write no session code. A session continues while the game has focus. After 30 minutes without focus or events, the next activity ends the old session with session_end (duration_s) and starts a new one. A session is also at most 24 hours old, so a game that stays open gets a new session every 24 hours.

If the game crashes or is killed while it has focus, the next launch ends the old session at its last activity and sends app_unclean_exit. A mobile game that the operating system closes in the background is not a crash.

Manalens.SessionId is the current session ID, and Manalens.AnonymousId is the player ID. Send the two to your backend when a server event, for example a purchase check, must be in the session of the player.

Sources: Manalens Unity SDK documentation.

How do I set the version and the build number?

Set them once, in Init(). AppVersion defaults to Application.version, which Unity reads from the Version field in Edit, Project Settings, Player. Build has no default: pass your build number, up to 64 characters. Storefront takes steam, itch, epic, gog, app_store, play or other.

The values go on every event in context.app, with the platform and the engine unity. They are filters and breakdowns in every report, for example Build is 571. So you can compare retention, crashes and funnels between two builds without an extra property.

To see which players moved to a new build, send game_updated on the first launch after an update. The SDK does not send this event. Keep the last build in PlayerPrefs, as below, and call ReportUpdate() after Init().

C#

using System.Collections.Generic;
using UnityEngine;
using ManalensSdk;

public static class BuildInfo
{
    public const string Build = "571"; // write this value from your build script

    // Call once, after Manalens.Init().
    public static void ReportUpdate()
    {
        string lastBuild = PlayerPrefs.GetString("analytics_last_build", "");
        string lastVersion = PlayerPrefs.GetString("analytics_last_version", "");
        if (lastBuild != "" && lastBuild != Build)
        {
            Manalens.Track("game_updated", new Dictionary<string, object>
            {
                ["previous_version"] = lastVersion,
                ["previous_build"] = lastBuild,
            });
        }
        PlayerPrefs.SetString("analytics_last_build", Build);
        PlayerPrefs.SetString("analytics_last_version", Application.version);
        PlayerPrefs.Save();
    }
}

Sources: Manalens Unity SDK and app events documentation; Unity Scripting API, Application.version and PlayerPrefs.

What changes on each platform?

The code stays the same. The quit, the storage and the network rules change. The table lists what the SDK documentation and the Unity Scripting API say for each platform.

If your game shows its own quit dialog on desktop, set HandleQuit to false and run the coroutine below before Application.Quit().

Platform notes for the Unity SDK.
PlatformPlatform value on eventsWhat to know
Windows, macOS, Linuxwindows, macos, linuxThe SDK handles the quit request (Application.wantsToQuit), sends session_end and flushes for at most 2 seconds. Events are saved in Application.persistentDataPath.
Android, iOSandroid, iosThese platforms do not report a quit, so the SDK saves everything and sends the queue when the game loses focus or is paused. Unity says that wantsToQuit cannot prevent termination on iOS and is not always raised on Android.
WebGLwebThe queue is kept in PlayerPrefs. The browser sends an Origin header, so the build must run on your project domain, a subdomain, or a host in Allowed origins. *.itch.zone is allowed by default.
Consoles, tvOS, visionOSotherEvents have the platform value other. No other behaviour is documented for these platforms.

C#

using System.Collections;
using UnityEngine;
using ManalensSdk;

public class QuitDialog : MonoBehaviour
{
    // Call this from the "Quit" button of your own dialog.
    public void OnQuitConfirmed() => StartCoroutine(QuitGame());

    IEnumerator QuitGame()
    {
        yield return Manalens.Shutdown(); // session_end, then a flush of at most QuitTimeoutSeconds
        Application.Quit();
    }
}

Sources: Manalens Unity SDK and app events documentation; Unity Scripting API, Application.wantsToQuit and Application.persistentDataPath.

How do I check that the data arrives?

Run a development build with the Debug option on, and read the activity feed. The SDK sends events every 10 seconds, at 20 queued events, on focus loss or pause, and on quit. So the first events appear some seconds after the launch.

The Flushed event tells you the result of each send. Add the line below while you test.

  1. Create a test project in Manalens and use its Publishable key, so that test data stays out of the real project.
  2. Set Debug = true in the options. The SDK then logs each queued event and each failed send.
  3. Make a development build and run it. With Enabled = !Application.isEditor, Play mode in the editor sends nothing.
  4. Open the activity feed. Check that session_start and game_open arrive, and that the event detail shows platform, storefront, app version, build and engine.
  5. Play one level and quit. Check level_start, level_complete and session_end with duration_s.
  6. Switch off the network, play for a minute, switch it on, and check that the queued events arrive once.
  7. Replace the test key with the production Publishable key, and set Debug to false.

C#

Manalens.Flushed += (sent, ok) => Debug.Log($"Analytics sent {sent} events, ok: {ok}");

Sources: Manalens Unity SDK documentation.

Which errors are common, and how do I fix them?

Most problems are a wrong key, a wrong host or the editor switch. The SendFailed event gives the HTTP status of a refused batch, or 0 when the SDK dropped the events itself.

Common errors with the Unity SDK, the cause and the fix.
SymptomCauseFix
Init() returns falseAn option is wrong, for example no endpoint, or a Secret key in PublishableKeyRead the reason in the log. Use the Publishable key and the collector URL without /v0/events.
"Init() was already called" in the logAwake() ran again because the first scene loaded againCheck Manalens.IsInitialized before Init().
No events from the editorEnabled = !Application.isEditor turns the SDK off in Play modeTest in a build, or send from the editor with the key of a test project.
Editor sessions in real reportsBy default the SDK sends events from every runSet Enabled = !Application.isEditor.
SendFailed with status 401The key is missing or is not a Publishable keyCopy the Publishable key again from the project Settings.
SendFailed with status 403 in a WebGL buildThe page host is not the project domain, a subdomain or an allowed originAdd the host under Project settings, Allowed origins.
SendFailed with status 400The collector refused the batch (INVALID_EVENT)Read the reason in the warning. The SDK does not send the batch again.
SendFailed with status 0The queue was over MaxQueue, or events were older than 7 daysThese events cannot be sent. Check the network of the test device.
Flushed with ok falseA network error, or a 5xx, 408 or 429 responseNo action. The events stay queued, and the SDK waits longer before each retry, at most 5 minutes.
A property is not on the eventThe value was a list, a dictionary or an objectSend strings, numbers, booleans or null.

Sources: Manalens Unity SDK, events API and app events documentation.

What will I see in the reports?

Create the Game KPIs board from the dashboard templates. It shows D1, D7 and D30 retention, DAU, MAU, stickiness, sessions per DAU, session length, ARPDAU, ARPPU, install cohorts, a level funnel, a levels table and currency sources and sinks. The Game health board shows crash-free sessions and players, errors per session by build and the top errors.

To connect play to marketing, set Storefront and link the game to your website. Install attribution links a first launch to a recent website visit on the same network. For a certain link, open your website from the game with LinkUrl(), or call Identify() with the same user ID on both sides.

C#

Application.OpenURL(Manalens.LinkUrl("https://example.com/wiki"));

Sources: Manalens dashboards, error tracking and install attribution documentation.

How do I start?

Manalens is the analytics and growth engine built for games. Install the Unity SDK, create the Game KPIs board, and see your players next to the channels that brought them.

Sources: Manalens product documentation.

Frequently asked questions

Which Unity versions does the Manalens SDK support?

Unity 2021.3 or later. The SDK is a Unity Package Manager package in plain C#, with no dependencies and no native code. It runs on Windows, macOS, Linux, Android, iOS and WebGL. On consoles, tvOS and visionOS, events have the platform value other.

Is the Unity SDK in a public package registry?

Not yet. During early access, the package is available on request from the contact page, and the source will be published at launch. You install it with the Package Manager from a folder or from a .tgz file, so the project needs no scoped registry.

Does the SDK send events from the Unity editor?

Yes, by default it sends from every run, also from Play mode. Test sessions and errors then mix into retention and crash-free reports. Set Enabled = !Application.isEditor in the options. To test the SDK in the editor, use a separate test project and its own Publishable key.

Does the SDK work offline?

Yes. The SDK saves events on disk, sends them in batches and retries them. The collector accepts app events up to 7 days old. So a player who plays offline for a few days still sends those events later, when the device is online again.

Sources and implementation