> ## Documentation Index
> Fetch the complete documentation index at: https://docs.manalens.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Unity SDK

> Track sessions, launches, game events, errors and crashes from Unity on desktop, mobile and WebGL.

The Unity SDK is a Unity Package Manager package in plain C#. It has no dependencies and no native code, so it works on Windows, macOS, Linux, Android, iOS and WebGL. It needs Unity 2021.3 or later. It sends [app events](https://docs.manalens.dev/sdks/app-events.md) to the normal events endpoint with your project's [Publishable key](https://docs.manalens.dev/api/authentication.md#publishable-key). It sends the same events as the [Godot SDK](https://docs.manalens.dev/sdks/godot.md).

## Install

> [!NOTE]
>
> **Early access.** The Unity package is available on request during early access. The repository is private until launch, so the steps below work only after you have access. To ask for it, use the Contact page of the ManaLens website (`/contact`) and tell us your engine and platform. The source will be published at launch.

1. In Unity, open **Window > Package Manager**. Click **+** and choose **Add package from git URL**.
2. Enter `https://github.com/manalens/manalens.git?path=sdks/unity`. To pin a version, add a tag or commit after `#`.
3. Copy the **Publishable key** from your project's **Settings**. It starts with `ua_pk_` (older projects: `ua_`). It is safe to ship in a game build. Never put a Secret key or an API key in a build: `Init()` refuses them.

> [!NOTE]
>
> The SDK is in the private ManaLens repository for now. It moves to its own public repository at launch. Then the git URL changes. If you received the package as a folder or a `.tgz` file, choose **Add package from disk** or **Add package from tarball** in step 1.

You can also add it to `Packages/manifest.json`:

```json theme={null}
{
  "dependencies": {
    "com.untitledanalytics.sdk": "https://github.com/manalens/manalens.git?path=sdks/unity"
  }
}
```

## Start the SDK

Start the SDK once, on the main thread, for example in the `Awake()` of a component in your first scene. The package sample **Basic setup** has this component.

```csharp theme={null}
using UnityEngine;
using UntitledAnalyticsSdk;

public class AnalyticsBootstrap : MonoBehaviour
{
    void Awake()
    {
        UntitledAnalytics.Init(new UntitledAnalyticsOptions
        {
            PublishableKey = "YOUR_PUBLISHABLE_KEY",
            Endpoint = "https://YOUR_COLLECTOR_ENDPOINT",
            Build = "571",
            Storefront = "steam",
            Enabled = !Application.isEditor,
        });
    }
}
```

`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.

| Option | Default | Meaning |
| - | - | - |
| `PublishableKey` | required | The project's Publishable key. |
| `Endpoint` | required | The collector URL, without `/v0/events`. |
| `AppVersion` | `Application.version` | Up to 32 characters, for example `1.4.0`. |
| `Build` | none | Up to 64 characters, for example a build number. |
| `Storefront` | none | `steam`, `itch`, `epic`, `gog`, `app_store`, `play` or `other`. |
| `Enabled` | `true` | `false`: the SDK sends nothing, writes no files and keeps no ID. See [Editor runs](#editor-runs). |
| `ConsentRequired` | `false` | No events and no stored ID until `SetConsent(true)`. |
| `FlushIntervalSeconds` | `10` | Seconds between sends. |
| `FlushAt` | `20` | Send when this many events are queued. Also the batch size (at most 50). |
| `MaxQueue` | `1000` | Most events kept on disk. The oldest are dropped first. |
| `HandleQuit` | `true` | Desktop players: delay the quit to send `session_end` and flush. |
| `QuitTimeoutSeconds` | `2` | Longest wait on quit. |
| `CaptureErrors` | `true` | Send exceptions, `Debug.LogError` and failed asserts as `error` events. |
| `CaptureWarnings` | `false` | Also send `Debug.LogWarning` messages. |
| `MaxAutoErrorsPerSession` | `50` | Most captured errors in one session. |
| `BeforeSend` | none | A function that gets the properties of each `error` event. Return them (changed or not), or `null` to drop the error. |
| `Debug` | `false` | Log each queued event and each failed send. |

## Track events

```csharp theme={null}
using System.Collections.Generic;

UntitledAnalytics.Track("level_complete", new Dictionary<string, object> { ["level"] = 3, ["attempt"] = 1, ["score"] = 1200 });
UntitledAnalytics.Track("resource", new Dictionary<string, object> { ["flow"] = "sink", ["currency"] = "gold", ["amount"] = 50, ["item"] = "sword" });
UntitledAnalytics.Identify("player_42", new Dictionary<string, object> { ["plan"] = "supporter" });
UntitledAnalytics.Reset(); // on sign out
```

Property values are strings, numbers, booleans or null. An enum value is sent as its name. The SDK drops other values (lists, dictionaries, objects) and logs a warning. Numbers are written with the invariant culture, so a player with a German or French system locale sends `1.5`, not `1,5`. Use the [event conventions](https://docs.manalens.dev/sdks/app-events.md#event-conventions) so that reports and funnels line up across games.

`Track()` can be called from any thread. The SDK sends from the main thread only.

## Open your website from the game

Use `LinkUrl()` when the game opens a page on your website (wiki, store, newsletter, Discord page). The website then joins this player, without `Identify()`:

```csharp theme={null}
Application.OpenURL(UntitledAnalytics.LinkUrl("https://example.com/wiki"));
```

`LinkUrl()` adds `ua_hid=<anonymous ID>.<unix seconds>` to the URL and keeps the query and the `#` part. The website needs the [Web SDK](https://docs.manalens.dev/sdks/web.md#players-who-come-from-your-game). The link works for 10 minutes. Before consent, `LinkUrl()` returns the URL unchanged. See [one player on the website and in the game](https://docs.manalens.dev/guides/identify-users.md#one-player-on-the-website-and-in-the-game).

## Errors and crashes

```csharp theme={null}
UntitledAnalytics.TrackError("Save failed", new TrackErrorOptions { ErrorType = "SaveFailed", Severity = "critical", Handled = false });

try { LoadSave(); }
catch (Exception e) { UntitledAnalytics.TrackError(e); } // type, message, stack and place in the code

UntitledAnalytics.SetBeforeSend(props => props); // return null to drop
```

The SDK also sends unhandled exceptions, `Debug.LogError` and failed asserts. It reads them with `Application.logMessageReceivedThreaded`, so errors from other threads count too. Warnings are off by default (`CaptureWarnings`). When a run crashes, the next launch sends `app_unclean_exit` in the crashed session. See [Errors and crashes](https://docs.manalens.dev/features/error-tracking.md) for the properties, the limits and the **Game health** board.

In release builds, Unity stack traces may have no file and line. Then the SDK groups errors by the function, or by the message without numbers.

## Editor runs

By default the SDK sends events from every run, also when you press Play in the editor. Test sessions, crashes and errors then mix into your real reports (crash-free sessions, errors by build, retention). Turn the SDK off in the editor:

```csharp theme={null}
UntitledAnalytics.Init(new UntitledAnalyticsOptions
{
    PublishableKey = "YOUR_PUBLISHABLE_KEY",
    Endpoint = "https://YOUR_COLLECTOR_ENDPOINT",
    Enabled = !Application.isEditor,
});
```

With `Enabled = false`, every call (`Track`, `Identify`, `SetConsent`, `Flush`) does nothing. To test the SDK in the editor, use a separate test project and its own publishable key.

The SDK works with **Enter Play Mode Options** (domain reload off): it resets its static state at `RuntimeInitializeLoadType.SubsystemRegistration`.

## Events

| Event | When |
| - | - |
| `UntitledAnalytics.Flushed(int sent, bool ok)` | After each send. `ok` is `false` for a network error or a `5xx`, `408` or `429` response; those events stay queued. |
| `UntitledAnalytics.SendFailed(int status, int dropped)` | Events were dropped and will never be sent. `status` is the HTTP status when the collector refused a batch (another `4xx`), or `0` when the SDK dropped events itself (the queue was over `MaxQueue`, or events were older than 7 days). |

```csharp theme={null}
UntitledAnalytics.SendFailed += (status, dropped) => Debug.LogWarning($"Analytics dropped {dropped} events ({status})");
```

## Sessions

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: a game that stays open gets a `session_end` and a `session_start` every 24 hours. Earlier builds of the SDK kept one session for as long as the game had focus. 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 OS closes in the background is not a crash. `OnApplicationFocus` and `OnApplicationPause` save the state and send the queue.

`UntitledAnalytics.SessionId` is the current session ID, and `UntitledAnalytics.AnonymousId` the player ID. Send the two to your backend to put a [server event](https://docs.manalens.dev/sdks/server.md#session-id-of-the-client) (for example a purchase) in the player's session.

Every event has a session ID that is not the anonymous ID. The collector refuses other events (`SESSION_ID_REQUIRED`, `SESSION_ID_IS_ANONYMOUS_ID`: see [the session ID contract](https://docs.manalens.dev/api/events.md#the-session-id-contract)).

## Offline queue and retries

* Events are saved in `Application.persistentDataPath` (on WebGL: PlayerPrefs) and sent every 10 seconds, at 20 queued events, on focus loss or pause, and on quit.
* After a network error or a `5xx`, `408` or `429` response, the SDK keeps the batch and waits about 2, 4, 8 ... seconds (with jitter), at most 5 minutes. Other `4xx` responses drop the batch: it is not sent again, and the warning in the log has the reason of the collector (for example `INVALID_EVENT, SESSION_ID_REQUIRED: ...`).
* Events keep their original time. The collector accepts app events up to 7 days old, so the SDK drops queued events older than that.
* Each event has a `message_id`, so a retry never counts twice.

## Quit

In a desktop player the SDK handles the quit request (`Application.wantsToQuit`). It sends `session_end`, flushes for at most `QuitTimeoutSeconds`, then quits. `Application.quitting` always ends the session and saves the queue. Events that could not be sent stay on disk for the next launch. iOS and Android do not report a quit: the SDK saves everything when the game is paused.

If your game handles the quit itself, set `HandleQuit` to `false` and run this before `Application.Quit()`:

```csharp theme={null}
IEnumerator QuitGame()
{
    yield return UntitledAnalytics.Shutdown();
    Application.Quit();
}
```

## Consent

```csharp theme={null}
UntitledAnalytics.Init(new UntitledAnalyticsOptions { PublishableKey = "ua_pk_...", Endpoint = "https://...", ConsentRequired = true });
// Later, from your consent screen:
UntitledAnalytics.SetConsent(true);   // starts tracking; sends game_open
UntitledAnalytics.SetConsent(false);  // deletes the ID, the session and the queue
```

With `ConsentRequired`, the SDK records no events and writes no ID before consent. It saves the choice, so the next launch uses it. An `Identify()` call before consent is sent after consent.

An opt-out fails closed:

* `SetConsent(false)` also writes a separate marker file (`untitled_analytics_optout`). While it exists, the SDK stays off, whatever the state file says. `SetConsent(true)` removes it.
* If a write fails, the SDK stays off and tries the write again every `FlushIntervalSeconds`.
* If the saved state exists but cannot be read, the SDK stays off in that run and does not change the file. If it is damaged (for example a cut-off write), the SDK keeps a copy (`untitled_analytics_state_corrupt`) and stays off until `SetConsent(true)`. Only a missing file means a first launch.
* Every file is written to a temporary file first and then renamed, so a crash during a write keeps the old file.

## Data the SDK sends

Each event carries `anonymous_id` (a random UUID kept in `Application.persistentDataPath`), `session_id`, `user_id` after `Identify()`, `context.locale` and `context.app`:

* `platform` from `Application.platform`: `windows`, `macos`, `linux`, `android`, `ios`, `web` or `other` (consoles, tvOS, visionOS).
* `engine`: `unity`.
* `app_version` (default `Application.version`), `build` and `storefront`.

The SDK sends no device ID, no hardware details and no IP. The collector derives the country from the request IP and does not store the IP.

## WebGL

A WebGL build runs in a browser, so its requests carry an `Origin` header. The collector accepts them from your project domain, its subdomains and `*.itch.zone` (itch.io). For another game portal, add its hosts to **Project settings > Allowed origins**. See [Web exports and CORS](https://docs.manalens.dev/sdks/app-events.md#web-exports-and-cors).

## Test locally

The core of the SDK has no Unity reference, so it builds and runs with the .NET SDK. From the repository:

```bash theme={null}
pnpm test:unity        # dotnet test (core), a compile check of the Unity layer, .meta files
pnpm test:unity:local  # a console runner sends real events to a local API and checks Tinybird raw_events
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.