Unity
Contents
Note: This SDK is currently in beta. Please report any issues on GitHub.
This is the official PostHog SDK for Unity. It uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your Unity game or application.
PostHog Unity SDK supports Windows, Mac, Linux, iOS, Android, and WebGL platforms.
Installation
PostHog is available for Unity via the Unity Package Manager.
Requirements
- Unity 2021.3 LTS or later
- .NET Standard 2.1 API Compatibility Level
Via Unity Package Manager (Git URL)
- Open Window > Package Manager
- Click the + button and select Add package from git URL
- Enter:
https://github.com/PostHog/posthog-unity.git?path=com.posthog.unity
Via local package
- Clone or download the posthog-unity repository
- Open Window > Package Manager
- Click the + button and select Add package from disk
- Navigate to
com.posthog.unity/package.json
Configuration
There are two ways to configure PostHog in Unity:
Option 1: Unity Inspector (recommended)
The easiest way to configure PostHog is through the Unity Inspector:
- Go to Edit > Project Settings > PostHog (this creates a settings asset if one doesn't exist)
- Enter your API Key and select your Host (US or EU Cloud)
- Configure other options as needed
The settings asset is created at Assets/Resources/PostHogSettings.asset. PostHog automatically initializes when your game starts using these settings.
You can also create the settings asset manually via Assets > Create > PostHog > Settings in Resources.
Tip: Click Test Connection in the Inspector to verify your API key is valid.
Option 2: Code-based initialization
For more control, initialize PostHog in your game's startup script:
Note: If you use code-based initialization, remove any
PostHogSettings.assetfrom your Resources folder to avoid double initialization.
Configuration options
All options below can be set via the Unity Inspector or in code:
Capturing events
You can send custom events using capture:
Tip: We recommend using a
[object] [verb]format for your event names, where[object]is the entity that the behavior relates to, and[verb]is the behavior itself. For example,project created,user signed up, orinvite sent.
Setting event properties
Optionally, you can include additional information with the event by including a properties object:
Capturing screen views
Track screen views to understand user navigation through your game:
Identifying users
We highly recommend reading our section on Identifying users to better understand how to correctly use this method.
When a user logs in, you can associate their events with their identity by calling IdentifyAsync:
Reset on logout
When a user logs out, call ResetAsync to clear the current user's identity and generate a new anonymous distinct ID:
Anonymous vs identified events
PostHog captures two types of events: anonymous and identified
Identified events enable you to attribute events to specific users, and attach person properties. They're best suited for logged-in users.
Scenarios where you want to capture identified events are:
- Tracking logged-in users in B2B and B2C SaaS apps
- Doing user segmented product analysis
- Growth and marketing teams wanting to analyze the complete conversion lifecycle
Anonymous events are events without individually identifiable data. They're best suited for web analytics or apps where users aren't logged in.
Scenarios where you want to capture anonymous events are:
- Tracking a marketing website
- Content-focused sites
- B2C apps where users don't sign up or log in
Under the hood, the key difference between identified and anonymous events is that for identified events we create a person profile for the user, whereas for anonymous events we do not.
Important: Due to the reduced cost of processing them, anonymous events can be up to 4x cheaper than identified ones, so we recommended you only capture identified events when needed.
Controlling person profiles
By default, the SDK captures identified events. To control whether events create person profiles, configure PersonProfiles during initialization:
Available options:
PersonProfiles.IdentifiedOnly(default) - Only creates person profiles whenIdentifyis calledPersonProfiles.Always- Creates person profiles for all eventsPersonProfiles.Never- Never creates person profiles (anonymous events only)
Super properties
Super properties are properties associated with events that are set once and then sent with every Capture call.
They are set using Register, which takes a key and value, and they persist across sessions.
This ensures that every event sent by the user will include these properties.
Removing super properties
Super properties are persisted across sessions so you have to explicitly remove them if they are no longer relevant:
If you are doing this as part of a user logging out you can instead simply use PostHog.ResetAsync() which takes care of clearing all stored super properties and more.
Group analytics
Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). Read the Group Analytics guide for more information.
Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more on the pricing page.
- Associate events with a group:
- Associate events with a group AND update group properties:
The name is a special property which is used in the PostHog UI for the name of the group. If you don't specify a name property, the group ID will be used instead.
Feature flags
PostHog's feature flags enable you to safely deploy and roll back new features as well as target specific users and groups with them.
Boolean feature flags
Multivariate feature flags
Feature flag payloads
Access payloads through the feature flag object:
Ensuring flags are loaded before usage
Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in storage.
This means that for most screens, the feature flags are available immediately – except for the first time a user visits.
To be notified when flags are loaded:
Reloading feature flags
Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call:
Overriding server properties for flags
You can set properties used for flag evaluation:
Experiments (A/B tests)
Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code:
It's also possible to run experiments without using feature flags.
Error tracking
The Unity SDK automatically captures unhandled exceptions and sends them to PostHog. This is enabled by default.
Manual exception capture
For handled exceptions that you want to report:
Configuration
Disabling error tracking
Application lifecycle events
When CaptureApplicationLifecycleEvents is enabled (default: true), these events are captured automatically:
Application Installed- First launchApplication Updated- Version changedApplication Opened- App foregroundedApplication Backgrounded- App backgrounded
Opt out of data capture
For GDPR compliance, you can disable data collection at any time:
Debug mode
If you're not seeing the expected events being captured or feature flags being evaluated, enable debug mode to see what's happening:
Available log levels: None, Error, Warning, Info, Debug
Manual flush
Force send all queued events immediately:
Shutdown
Clean up when your app exits:
Note: The SDK automatically flushes on app quit, so explicit shutdown is optional.
Platform support
| Platform | Support |
|---|---|
| Windows/Mac/Linux | Full |
| iOS | Full |
| Android | Full |
| WebGL | With limitations* |
| Consoles | Untested |
*WebGL uses PlayerPrefs for storage (limited size) and is subject to CORS restrictions.
Troubleshooting
Events not appearing in PostHog
- Check your API key is correct
- Verify the host URL matches your PostHog instance (e.g.,
https://us.i.posthog.comorhttps://eu.i.posthog.com) - Set
LogLevel = PostHogLogLevel.Debugto see detailed logs - Ensure you're not opted out (
PostHog.IsOptedOut)
WebGL issues
- Ensure your PostHog instance allows CORS from your domain
- WebGL has limited storage - consider reducing
MaxQueueSize
Demo
Check out Hedgehog Game, a sample Unity game that demonstrates how to integrate PostHog analytics.