Skip to content
Docs
FA
Sign in
Start here
  • Overview
  • Quickstart
  • Concepts
Collect data
  • Designing events
  • Event dictionary
  • Placing events
  • Identity
  • Web SDK
  • Android SDK
  • Unity SDK
  • Devices and push
  • Server to server
  • Product catalogue
  • Webhooks
Engage customers
  • Segments
  • Journeys
  • Transactional
  • Consent and caps
  • In-app and inbox
Analyze and export
  • Reports and exports
Developer reference
  • API reference
    • Ingest endpoints
    • Management API
  • Errors
  • Limits
  • OpenAPI
Developer tools
  • MCP server
  • Working with an agent
Privacy and changes
  • Personal data
  • Versioning

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 doesYou do
Sends events in batches and keeps them on disk while the player is offlineDecide which events to send and name them
Keeps the event ID on every retry so the collector can recognize duplicatesSend revenue only on events where money really moved
Retries with growing, randomised waits and says what it droppedCall Identify after your own sign-in
Saves the queue when the app goes to the backgroundGet the push token from your own push plugin
Registers the push token you give itAllow https://in.segmentic.net (or your own host) in your network rules

#Installing

  1. Download the Unity SDK 0.1.0 package and its SHA-256 checksum to the same folder.
  2. In that folder, run shasum -a 256 -c net.segmentic.sdk-0.1.0.tgz.sha256 on macOS or sha256sum -c net.segmentic.sdk-0.1.0.tgz.sha256 on Linux. Continue when the result is OK.
  3. Open Window > Package Manager in Unity. Use the + menu, choose Install package from tarball..., and select the .tgz file.
  4. 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

Boot.cs
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

C#
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 Done and level_done are two events for ever.
  • Properties are a Dictionary<string, object>. A Dictionary<string, int> does not convert; build the object one.
  • Numbers stay numbers, booleans stay booleans, and a numeric string stays a string: "2450000" will never match a "greater than" filter. A null value 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, value and the price with quantity pair add to a person's lifetime value on any event. See revenue.

#Who the player is

C#
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 Reset is called.
  • Identify with a user ID that differs from the saved one queues an alias first, then the identify. 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.
  • Reset forgets 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, call UnregisterDevice first (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 explicit UnregisterDevice queued before OptOut: 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:

C#
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 4xx answer means the server refused it and the same body would be refused again, so it is forgotten and GetStats().LastDeviceError says 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 400 to it. If the player turns notifications off, send new 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 call RegisterDevice again after Identify. Identifying a different player, or Reset, 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 answers 403 user identity is not verified unless you pass UserHash (an HMAC your backend makes for that user ID; also BindingId). Both are passed through as given; see Devices and push. Registering before sign-in, with no Identify yet, 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 same userHash your backend makes, so call it before Reset() or OptOut() 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 in LastDeviceError. A sign-out queued before OptOut() still retries while opted out; new registrations remain blocked. Pass revoked: true to revoke the device. SignOutPending in 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 ApiHost and WriteKey. Reopen with that configuration to retry it. If an upgrade reports a legacy sign-out in LastDeviceError, select the original collector and write key, then call UnregisterDevice again 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 iOS apns. 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 backWhat the SDK does
200Removes 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, 408Keeps everything and retries with a growing random wait: up to 2, 4, 8 ... 300 seconds. Retry-After is honoured when it is longer
413Halves 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

C#
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

PlatformEventsQueue survives a restartPush registration
Androidyesyesfcm, bazaar, myket, huawei
iOSyesyesapns
Windows, macOS, Linux players and the Editoryesyesregisters, but no campaign can deliver to these today
WebGLyesno: 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 againno

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.

PreviousAndroid SDKNextDevices and push

On this page

  • What it does and what stays with you
  • Installing
  • Starting it
  • Events
  • Who the player is
  • Push
  • Offline queue and retries
  • Looking at its health
  • Platforms
  • What is not in this version
  • What was run, and what was not

Segmentic

This page is written from the code