Install and use the Unity SDK
Install the package in Unity, send player events and register device push tokens.
The Unity SDK records events, remembers who the player is, keeps events while the phone is offline, and registers push tokens. Package Manager installs Unity’s built-in UnityWebRequest module with the SDK. The package contains C# and adds no external Android or iOS libraries.
It speaks the same wire protocol as the other SDKs. Everything on placing events, events and identity applies to it unchanged.
What it does and what stays with you
| The SDK does | You do |
|---|---|
| Sends events in batches and keeps them on disk while the player is offline | Decide which events to send and name them |
| Keeps the event ID on every retry so the collector can recognize duplicates | Send revenue only on events where money really moved |
| Retries with growing, randomised waits and says what it dropped | Call Identify after your own sign-in |
| Saves the queue when the app goes to the background | Get the push token from your own push plugin |
| Registers the push token you give it | Allow https://in.segmentic.net (or your own host) in your network rules |
Installing
- Download the Unity SDK 0.1.0 package and its SHA-256 checksum to the same folder.
- In that folder, run
shasum -a 256 -c net.segmentic.sdk-0.1.0.tgz.sha256on macOS orsha256sum -c net.segmentic.sdk-0.1.0.tgz.sha256on Linux. Continue when the result isOK. - Open Window > Package Manager in Unity. Use the + menu, choose Install package from tarball..., and select the
.tgzfile. - To update, install the newer tarball the same way. Scripts attached to objects keep their IDs between releases.
Version 0.1.0 was tested with Unity 6.6 (6000.6.8f1). Package Manager installs the built-in UnityWebRequest module automatically.
Starting it
using System.Collections.Generic;
using Segmentic;
using UnityEngine;
public class Boot : MonoBehaviour
{
void Start()
{
SegmenticSdk.Init(new SegmenticOptions
{
WriteKey = "wk_seg_...", // the public write key from the panel
ApiHost = "https://in.segmentic.net", // required: a self-hosted install has its own
});
SegmenticSdk.Track("level_completed", new Dictionary<string, object>
{
{ "level", 3 },
{ "score", 1200 },
});
}
}
No code? Add the Segmentic Initializer component (menu Component > Segmentic) to an object in your first scene and fill in the write key and host.
The write key is public and is meant to ship inside the build. ApiHost has no default on purpose: a default would send a self-hosted customer's events to the wrong place and fail with a 401 that looks like a bad key.
Call it from the main thread, which is where Unity code runs anyway. Init twice is safe: the second call returns the running client.
Events
SegmenticSdk.Track("product_viewed", new Dictionary<string, object> { { "product_id", "p-77" } });
SegmenticSdk.Screen("Shop");
- An empty event name is ignored and logged. Names follow the naming rule: no case folding, so
Level Doneandlevel_doneare two events for ever. - Properties are a
Dictionary<string, object>. ADictionary<string, int>does not convert; build theobjectone. - Numbers stay numbers, booleans stay booleans, and a numeric string stays a string:
"2450000"will never match a "greater than" filter. Anullvalue is left out. Dates become UTC ISO 8601 text, enums become their name, lists and nested dictionaries are written as JSON. - Numbers are written the same way whatever language the phone is set to. A Persian or Arabic phone does not change a decimal point.
- Do not build an event name from a variable. See when the name is a URL: the same mistake, in a game, is
"clicked_" + buttonName. revenue,total,valueand thepricewithquantitypair add to a person's lifetime value on any event. See revenue.
Who the player is
SegmenticSdk.Identify("user-42", new Dictionary<string, object> { { "city", "Tehran" } });
SegmenticSdk.Reset(); // on sign-out
- The SDK makes an anonymous ID the first time it runs and keeps it until the game is uninstalled or
Resetis called. Identifywith a user ID that differs from the saved one queues analiasfirst, then theidentify. What the player did before signing in joins the same profile. Calling it again with the same ID does not alias again, not even after a restart.Resetforgets the user and makes a new anonymous ID, so the next person on a shared device does not inherit the history. Events already queued keep the IDs they were made with. A push registration that is still waiting to be sent is discarded too, because it carries the old player's IDs. To also detach the phone from the old player on the server, callUnregisterDevicefirst (see Push).OptOut()stops collecting, clears the queue and the saved copy, and is remembered across restarts.OptIn()reverses it. While opted out no events or device registrations are queued or sent. The only exception is an explicitUnregisterDevicequeued beforeOptOut: that sign-out remains saved and retries, including after restart. A request already on the network cannot be recalled.
Event queues, pending device registrations, and identities belong to the exact collector URL and write key. Reopening with the original settings resumes its saved work. After upgrading from a version that did not record this destination, sign in and register the device again. Unattributed old events and registrations are never sent to the current collector. Opting out clears event and registration queues across saved destinations. If the consent marker cannot be read, collection stops. Resolve the storage problem and restart to read the saved decision, or call OptIn() after obtaining consent.
Explicit device sign-outs are delivered in order across account changes. For an exact legacy reclaim that also identifies a different current device, an opted-in client queues both sign-outs. While opted out it may reclaim only the matching legacy device. Drain sign-outs with their original settings before downgrading. An older binary can also read its old unscoped files, so do not reuse that save folder with a different collector on rollback.
Push
The SDK never asks the platform for a push token. Your game already has a push plugin; give the token to Segmentic when you get it, and again whenever it changes:
SegmenticSdk.RegisterDevice(new DeviceRegistration
{
Tokens = new Dictionary<string, string>
{
{ "fcm", firebaseToken },
{ "bazaar", bazaarToken }, // one device may carry several routes
},
});
- It goes to
POST /v1/devices, the same endpoint as the manual path, and not through the event batch. - It is saved and sent with the next flush (within about ten seconds, or call
await SegmenticSdk.FlushAsync()). If the network is down it is kept, also across restarts, and only the newest registration is kept. - A
4xxanswer means the server refused it and the same body would be refused again, so it is forgotten andGetStats().LastDeviceErrorsays why. It is a separate field so that a good event send cannot hide it. - No usable token and push not switched off is not sent, because the server answers
400to it. If the player turns notifications off, sendnew DeviceRegistration { PushEnabled = false }. - Register again after
Identify. A registration is made for whoever the player is at that moment. Registering before sign-in makes an anonymous install, which no campaign targets today (see anonymous installs); so callRegisterDeviceagain afterIdentify. Identifying a different player, orReset, discards a registration that was still waiting for the previous one. - A player who has been identified needs a proof from your backend. After
Identify, the registration carries the user ID, and the server answers403 user identity is not verifiedunless you passUserHash(an HMAC your backend makes for that user ID; alsoBindingId). Both are passed through as given; see Devices and push. Registering before sign-in, with noIdentifyyet, is accepted as an anonymous install. - Sign-out:
SegmenticSdk.UnregisterDevice(userId, userHash, bindingId)detaches the phone from that player on the server (sign-out). It needs the sameuserHashyour backend makes, so call it beforeReset()orOptOut()while you still have it, and check the returned boolean. It is saved, sent with the next flush, kept if the network is down, and a refused one is forgotten and shown inLastDeviceError. A sign-out queued beforeOptOut()still retries while opted out; new registrations remain blocked. Passrevoked: trueto revoke the device.SignOutPendingin the stats says one is waiting. Opting out alone does not automatically revoke a device. Upgrading cannot recover a sign-out that an older SDK already erased; downgrading while one is pending can cancel its retry. - The SDK saves each sign-out for its original
ApiHostandWriteKey. Reopen with that configuration to retry it. If an upgrade reports a legacy sign-out inLastDeviceError, select the original collector and write key, then callUnregisterDeviceagain with exactly the original user ID, user hash, binding and revoked flag. This works while opted out. The old record has no destination, so the SDK waits for that explicit call. Finish a pending sign-out before reclaiming a legacy one or downgrading. - Transports accepted for Android are
fcm,bazaar,myket,huawei; for iOSapns. The device ID is a random ID the SDK keeps in the app's own storage, never the advertising ID.
Offline queue and retries
Events are queued in memory, saved to the app's private folder every couple of seconds and whenever the app is paused or quits, and sent in batches of 20 (or every 10 seconds). The queue holds 1000 events; when it is full the oldest is dropped and counted.
| What comes back | What the SDK does |
|---|---|
200 | Removes the batch. Items the server refused one by one (rejected in the answer) are counted as dropped and never retried. Duplicates count as sent |
No answer, timeout, 5xx, 429, 408 | Keeps everything and retries with a growing random wait: up to 2, 4, 8 ... 300 seconds. Retry-After is honoured when it is longer |
413 | Halves the batch and goes again until it fits. A single event that is still too large is dropped and counted |
Any other 4xx (400, 401, 402, 403...) | Drops that batch and counts it: the server will refuse it identically every time. LastError holds the status |
Every event has its message_id from the moment it is made. A retry, or a send that was cut short by a crash, carries the same ID. The collector remembers IDs for a configured window (48 hours by default). A later retry or a deduplication store outage can produce a duplicate.
A hard crash can lose the events made in the last couple of seconds, because the save is not written on every call.
Looking at its health
var s = SegmenticSdk.GetStats();
// s.Queued, s.Sent, s.Dropped, s.OptedOut, s.DurableStorage, s.AnonymousId, s.UserId,
// s.LastError, s.LastDeviceError, s.DevicePending, s.SignOutPending
Set Log = Debug.Log in the options to see each decision in the Unity console. LastError of http 401 after a first install nearly always means a wrong write key or host, and LastDeviceError of http 403 means the push registration of a signed-in player had no UserHash. To see what arrived on the server, use seeing what actually arrived.
Platforms
| Platform | Events | Queue survives a restart | Push registration |
|---|---|---|---|
| Android | yes | yes | fcm, bazaar, myket, huawei |
| iOS | yes | yes | apns |
| Windows, macOS, Linux players and the Editor | yes | yes | registers, but no campaign can deliver to these today |
| WebGL | yes | no: memory only, DurableStorage is false. The anonymous ID and a signed-in user are forgotten too, so every page load is a new visitor until you call Identify again | no |
WebGL stores the consent flag in PlayerPrefs. Clearing site data clears that preference.
Plain http:// hosts are blocked by default on iOS and Android; use https://, or turn on Unity's "Allow downloads over HTTP" player setting for a self-hosted test box.
What is not in this version
Automatic push tokens, in-app messages, install attribution, crash reports, and automatic app_opened or session events (as the event dictionary says, no SDK sends those: send your own).
What was run, and what was not
Tested with Unity 6000.6.8f1 on macOS and, in the Android integration tests, a Xiaomi phone running Android 13 (ARM64 IL2CPP). The Android tests cover the SDK and device registration. Delivery of a real Firebase notification is a separate test.