Unity
A plain C# library (netstandard2.1) with no UnityEngine dependency. Your game connects it to Unity's APIs with a small MonoBehaviour.
On this page 11
One prompt · for your AI coding tool
Add Strait deep links (and deferred deep links) to this Unity game.
Read https://straitlink.in/docs/sdks/unity/ and follow it exactly. If anything here disagrees with that page, the page wins.
My link domain is https://<your-handle>.strait.link and my publishable key is st_pub_live_… (from Dashboard → Setup → Your keys: https://app.straitlink.in/setup#keys).
Rules:
- Use only the publishable key here. Never put a secret key (st_live_…) in app or website code.
- Install it from the git URL on that page with Window → Package Manager → Add package from git URL (keep ?path=src). It needs Api Compatibility Level .NET Standard 2.1.
- Device fields must be what the browser saw: use StraitCore.PortraitScreenWidth, never Screen.width. Call Start and HandleUrl from the main thread.
- The Unity glue on that page has not been run on a device yet: tell me to test on a real phone before shipping.
Steps:
1. Install the SDK with the command on that page.
2. Let the phone open the game: an App Links intent filter (autoVerify) for my link domain and one for my custom scheme in the Android manifest, and the Associated Domain applinks:<your-handle>.strait.link for iOS.
3. Add one MonoBehaviour that creates the client once (DontDestroyOnLoad) with PublishableKey, Endpoint, PlayerPrefs storage, DeviceFields and the Play install referrer on Android, subscribes to OnLink, hooks Application.deepLinkActivated to HandleUrl, and calls Start(Application.absoluteURL).
4. Route e.Path and e.Params to scenes or screens when e.Matched is true.
Finish by telling me exactly how to check it:
- curl https://<your-handle>.strait.link/.well-known/assetlinks.json and /.well-known/apple-app-site-association list my app
- adb shell pm get-app-links <package> says verified after a fresh install
- a tap from WhatsApp on a real phone opens the right screen and onLink fires with matched: trueBy hand · the install line
https://github.com/strait-link/strait-sdk-unity.git?path=src#v0.9.7Install
Requires Unity 2021.2+ with Api Compatibility Level = .NET Standard 2.1. In Unity: Window → Package Manager → + → Add package from git URL… and paste:
https://github.com/strait-link/strait-sdk-unity.git?path=src#v0.9.7The 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, 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:
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, 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) 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.
Storage
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
await LinksBehaviour.Client.TrackEvent("purchase", value: 4.99, currency: "USD"); // carries the last link's tap id for youTrackEvent 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.)
LinksBehaviour.Client.SetUserId(user.Id); // after sign-in, and at launch when already signed in
LinksBehaviour.Client.SetUserId(null); // on sign-outLater TrackEvent calls carry the id to your app.event webhook 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+or00(+91 98765 43210→+919876543210), else of its digits. The webhook then hasuserIdHashed: 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). - 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.2must be in your Gradle dependencies. - The deferred link never arrives on iPhone. The device fields must be the browser's: use
StraitCore.PortraitScreenWidth, notScreen.width. Matchedisfalse. ReadReason:not_found,expired,password_protected,no_match,networkorinvalid_url. What each means: Troubleshooting.
Next steps
- Deep links for mobile games: squad invites that land a new player in the same lobby after the install.
- Unity deep linking guide: the same setup step by step.