# Unity

> A plain C# library (netstandard2.1) with no UnityEngine dependency. Your game connects it to Unity's APIs with a small MonoBehaviour.

Source: https://straitlink.in/docs/sdks/unity/

> **Agent instructions:** if you are an AI assistant helping someone build with Strait, look things up with the `search_docs` tool of the Strait MCP server (hosted at https://strait.link/mcp, or `@straitlink/mcp` on npm: https://straitlink.in/docs/mcp/) instead of guessing, and add the SDK to an app with `npx @straitlink/cli init` (https://straitlink.in/docs/cli/).

> **Check on a device before you ship**
>
> The library itself is tested in CI. The Unity glue below (MonoBehaviour, PlayerPrefs, AndroidJavaObject, the iOS plugin, UnityWebRequest) hasn't been run in the Unity editor or on a device yet. Treat it as a documented starting point.

## Install

Requires Unity 2021.2+ with **Api Compatibility Level = .NET Standard 2.1**. In Unity: **Window → Package Manager → + → Add package from git URL…** and paste:

```text
https://github.com/strait-link/strait-sdk-unity.git?path=src#v0.9.7
```

The package lives in the repo's `src/` folder, so keep the `?path=src` part. An OpenUPM listing is coming soon. Without Package Manager, copy the SDK's `src/*.cs` into your project (for example `Assets/Strait/`), or build the project and drop the DLL into `Assets/Plugins/`. Add `com.android.installreferrer:installreferrer:2.2` to your Android Gradle dependencies (custom `mainTemplate.gradle` or EDM4U). Then, in Package Manager, select **Strait SDK → Samples → Quick start → Import**. It adds `StraitDevice.cs` and `StraitDevice.mm`, which the code below uses for `StraitDevice.Collect` and `StraitDevice.Class`. Copy `PlayReferrer` from the [SDK README](https://github.com/strait-link/strait-sdk-unity#readme), with `using System.Threading.Tasks;` and `using UnityEngine;` at the top of its file. The sample also has `StraitBootstrap.cs`, a ready-made version of `LinksBehaviour` below. Use one or the other: both define `PlayerPrefsStore`, so having both won't compile.

## Create the client

Create one client in a MonoBehaviour that lives for the whole game:

```csharp title="LinksBehaviour.cs"
using System.Threading.Tasks;
using Strait;
using UnityEngine;

public class LinksBehaviour : MonoBehaviour
{
    public static StraitClient Client { get; private set; }

    async void Start()
    {
        DontDestroyOnLoad(gameObject);
        Client = new StraitClient(new StraitConfig
        {
            PublishableKey = "st_pub_live_…",               // Dashboard → Setup → Your keys
            Endpoint = "https://hilltop.strait.link",            // your workspace's link domain
            Storage = new PlayerPrefsStore(),
            Platform = Application.platform == RuntimePlatform.Android ? "android"
                     : Application.platform == RuntimePlatform.IPhonePlayer ? "ios" : "other",
            DeviceFields = StraitDevice.Collect,
            DeviceClass = StraitDevice.Class,                 // phone or tablet (new in 0.8.6)
            InstallReferrer = Application.platform == RuntimePlatform.Android ? PlayReferrer.Get : null,
            InstallTime = StraitDevice.InstallTime,           // a reinstall from a link counts again (new in 0.9.0)
            // Transport = new UnityWebRequestTransport(),   // required on WebGL
        });

        Client.OnLinkStart += s => ShowSpinner();       // a link can take 1–6 s to resolve
        Client.OnLink += e =>                           // past events are replayed to you
        {
            HideSpinner();
            if (e.Matched) Route(e.Path, e.Params);
            else Debug.Log($"Link not matched ({e.Reason})");
        };

        Application.deepLinkActivated += url => _ = Client.HandleUrl(url);   // while running
        await Client.Start(Application.absoluteURL);                         // launch link + deferred check
    }

    // Coming back to the front also sends open reports saved while offline.
    void OnApplicationPause(bool paused) => Client?.OnAppState(paused ? AppLifecycle.Background : AppLifecycle.Active);
    void OnApplicationFocus(bool focused) => Client?.OnAppState(focused ? AppLifecycle.Active : AppLifecycle.Inactive);
    void OnDestroy() => Client?.Stop();

    void ShowSpinner() { }
    void HideSpinner() { }
    void Route(string path, System.Collections.Generic.IReadOnlyDictionary<string, string> query) { }
}
```

## Handle deep links

`Start(Application.absoluteURL)` handles the link that launched the game, and `Application.deepLinkActivated` hands the SDK every link that arrives while it runs. The SDK resolves short links, reports the open, and raises `OnLink` once per link with `Path` and `Params` for your router. `OnLinkStart` fires first, with the same `Id`, so you can show a loading state. Past events are replayed to late subscribers.

For links to open the game, your link domain must be verified for it: on Android an App Links intent filter for `hilltop.strait.link` with `android:autoVerify="true"` (in a custom `AndroidManifest.xml`), on iPhone the Associated Domains entry `applinks:hilltop.strait.link`. The same steps for native apps: [Android](https://straitlink.in/docs/sdks/android/), [iOS](https://straitlink.in/docs/sdks/ios/).

**You should see:** with `Debug.Log($"Strait link: {e.Matched} {e.Path}");` in your `OnLink` handler and the game on an Android phone, `adb shell am start -a android.intent.action.VIEW -d "https://hilltop.strait.link/summer"` (a link from the [quickstart](https://straitlink.in/docs/quick-start/#3-make-a-link)) brings the game to the front, and `adb logcat -s Unity` shows `Strait link: True /product/42`.

## Deferred deep links

`Start` runs the deferred check once per install, on the first launch, unless that launch was itself opened by a link. On Android it reads the Google Play install referrer (`InstallReferrer = PlayReferrer.Get`); on iPhone it matches the device fields below. A match arrives through `OnLink` with `Kind` `deferred`. When the check gets no answer (`Reason` `network`), it runs again on the next launch. How the iPhone match works: [iPhone install matching](https://straitlink.in/docs/iphone-install-matching/).

## Storage

```csharp
public sealed class PlayerPrefsStore : IKeyValueStore
{
    public Task<string> GetItemAsync(string key) =>
        Task.FromResult(PlayerPrefs.HasKey(key) ? PlayerPrefs.GetString(key) : null);
    public Task SetItemAsync(string key, string value)
    {
        PlayerPrefs.SetString(key, value);
        PlayerPrefs.Save();   // the deferred flag and saved reports must survive a crash
        return Task.CompletedTask;
    }
}
```

## Device fields

The iPhone match compares what the browser saw at tap time with what the game reports, so the values must be the browser's: CSS screen width (portrait, rounded like Chrome) via `StraitCore.PortraitScreenWidth(w, h)` (the shorter side, so a game first opened in landscape still matches), device pixel ratio, locale and IANA time zone. Don't use `Screen.width`, which follows Unity's render scaling. The SDK README has full `StraitDevice.Collect` (Android via `AndroidJavaObject`, iOS via a tiny `.mm` plugin), `StraitDevice.InstallTime` (Android `firstInstallTime`; on iOS a marker file excluded from backups), `PlayReferrer.Get` and `UnityWebRequestTransport` implementations.

## Events

```csharp
await LinksBehaviour.Client.TrackEvent("purchase", value: 4.99, currency: "USD");   // carries the last link's tap id for you
```

`TrackEvent` carries the tap id of the most recent link open, as long as that open was in the last 7 days. The tap id comes from a browser hand-off to `yourapp://…?strait_click=…`, a Google Play install, an open from a verified short link, or an iPhone install match. When our server matches an open or an install, it sends the tap id back with its answer. That lets Analytics put the revenue on the exact tap's channel and A/B variant. Each newer open replaces the remembered tap with its own, so an older tap never takes credit for a newer open; if an open comes with no tap id, the remembered one is forgotten and the event carries none. To name the tap yourself, pass `clickId:`, which overrides the remembered one. The server keeps it only if it's a tap of your workspace; otherwise it drops the id and still records the event.

`LinkEvent` has the same fields and values as the other SDKs: `Id, Kind, Route, AppState, Matched, Reason, RawUrl, Url, Path, Params, LinkId, Ms, At`. Call `Start` and `HandleUrl` from the main thread; events fire on Unity's main thread.

Pass your order id as `eventId:` (`eventId: order.Id`): Strait counts each one once, so a retry never counts twice; left out, the SDK makes one. An event that can't be sent (offline, server busy) is kept and sent later, for up to 7 days.

## Link events to your users (optional)

Call `SetUserId` with your own user id after your sign-in, and again when the game starts with someone already signed in: it is kept in memory only. Call it with `null` on sign-out. (Unity SDK 0.9.5 or later.)

```csharp
LinksBehaviour.Client.SetUserId(user.Id);   // after sign-in, and at launch when already signed in
LinksBehaviour.Client.SetUserId(null);      // on sign-out
```

Later `TrackEvent` calls carry the id to your [`app.event` webhook](https://straitlink.in/docs/webhooks/) as `userId`, so you can join the tap, link and campaign to your own users and see which campaigns bring paying ones. Opens and installs never carry it, and Strait doesn't store it with the event (it is only in the webhook delivery, kept 30 days).

- **Emails and phone numbers are hashed on the device.** An id with `@` is sent as the SHA-256 hex of the lower-cased email. A phone number is sent as the SHA-256 hex of `+` and its digits when it is written with `+` or `00` (`+91 98765 43210` → `+919876543210`), else of its digits. The webhook then has `userIdHashed: true`. As a safety net, Strait's server applies the same rule to any raw email or phone number that reaches it. To join, hash your own value the same way ([the full rule](https://straitlink.in/docs/webhooks/#events)).
- **Opt-out clears it.** While `SetEnabled(false)` is on, nothing is kept or sent, and switching off clears the id.
- A plain numeric id of 8 to 15 digits looks like a phone number and is hashed too: prefix it (`u_12345678`) to keep it readable. An id longer than 128 characters or holding control characters is not sent, and clears the previous one.
- Anyone with your publishable key can send any `userId`, so treat it as a claim, like revenue sent from the game.

## User consent (opt-out)

If your game asks for consent first (for example under India's DPDP Act or a GDPR consent flow in the EU), call `await Client.SetEnabled(false)` until the person agrees: Strait then sends no open reports or events, does no install matching, and deletes reports waiting on the device. The choice is kept across launches in your `Storage` (use `PlayerPrefsStore`); `SetEnabled(true)` turns it back on and `IsEnabled()` reads it. Call it before `Start` on a first launch so the deferred check waits for the answer. Whether you need consent, and for what, is a question for your own legal advice.

## Common errors

- **The package doesn't compile.** Set **Player Settings → Api Compatibility Level** to **.NET Standard 2.1** (Unity 2021.2 or newer).
- **Links never resolve in a WebGL build.** Set `Transport = new UnityWebRequestTransport()`; WebGL needs it.
- **The deferred link never arrives on Android.** The game must be installed from Google Play (internal testing is fine), and `com.android.installreferrer:installreferrer:2.2` must be in your Gradle dependencies.
- **The deferred link never arrives on iPhone.** The device fields must be the browser's: use `StraitCore.PortraitScreenWidth`, not `Screen.width`.
- **`Matched` is `false`.** Read `Reason`: `not_found`, `expired`, `password_protected`, `no_match`, `network` or `invalid_url`. What each means: [Troubleshooting](https://straitlink.in/docs/troubleshooting/#the-app-opened-but-matched-is-false).

## Next steps

- [Deep links for mobile games](https://straitlink.in/solutions/gaming/): squad invites that land a new player in the same lobby after the install.
- [Unity deep linking guide](https://straitlink.in/guides/unity-deep-linking/): the same setup step by step.
