Skip to content

Commit 4e66cae

Browse files
authored
feat(docs): First pass at posthog-unity docs (#14090)
* First pass at posthog-unity docs * Fix available log levels.
1 parent 173c649 commit 4e66cae

File tree

6 files changed

+536
-0
lines changed

6 files changed

+536
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
PostHog is available for Unity via the [Unity Package Manager](https://docs.unity3d.com/Manual/upm-ui.html).
2+
3+
### Requirements
4+
5+
- Unity 2021.3 LTS or later
6+
- .NET Standard 2.1 API Compatibility Level
7+
8+
### Via Unity Package Manager (Git URL)
9+
10+
1. Open **Window > Package Manager**
11+
2. Click the **+** button and select **Add package from git URL**
12+
3. Enter: `https://github.com/PostHog/posthog-unity.git?path=com.posthog.unity`
13+
14+
### Via local package
15+
16+
1. Clone or download the [posthog-unity repository](https://github.com/PostHog/posthog-unity)
17+
2. Open **Window > Package Manager**
18+
3. Click the **+** button and select **Add package from disk**
19+
4. Navigate to `com.posthog.unity/package.json`
20+
21+
### Configuration
22+
23+
There are two ways to configure PostHog in Unity:
24+
25+
#### Option 1: Unity Inspector (recommended)
26+
27+
The easiest way to configure PostHog is through the Unity Inspector:
28+
29+
1. Go to **Edit > Project Settings > PostHog** (this creates a settings asset if one doesn't exist)
30+
2. Enter your **API Key** and select your **Host** (US or EU Cloud)
31+
3. Configure other options as needed
32+
33+
The settings asset is created at `Assets/Resources/PostHogSettings.asset`. PostHog automatically initializes when your game starts using these settings.
34+
35+
You can also create the settings asset manually via **Assets > Create > PostHog > Settings in Resources**.
36+
37+
> **Tip:** Click **Test Connection** in the Inspector to verify your API key is valid.
38+
39+
#### Option 2: Code-based initialization
40+
41+
For more control, initialize PostHog in your game's startup script:
42+
43+
```csharp
44+
using PostHog;
45+
using UnityEngine;
46+
47+
public class GameManager : MonoBehaviour
48+
{
49+
void Start()
50+
{
51+
PostHog.Setup(new PostHogConfig
52+
{
53+
ApiKey = "<ph_project_api_key>",
54+
Host = "<ph_client_api_host>" // usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
55+
});
56+
}
57+
}
58+
```
59+
60+
> **Note:** If you use code-based initialization, remove any `PostHogSettings.asset` from your Resources folder to avoid double initialization.
61+
62+
### Configuration options
63+
64+
All options below can be set via the Unity Inspector or in code:
65+
66+
```csharp
67+
PostHog.Setup(new PostHogConfig
68+
{
69+
// Required
70+
ApiKey = "<ph_project_api_key>",
71+
72+
// Optional
73+
Host = "<ph_client_api_host>", // PostHog instance URL (default: https://us.i.posthog.com)
74+
FlushAt = 20, // Events before auto-flush (default: 20)
75+
FlushIntervalSeconds = 30, // Seconds between flushes (default: 30)
76+
MaxQueueSize = 1000, // Max queued events (default: 1000)
77+
MaxBatchSize = 50, // Max events per request (default: 50)
78+
CaptureApplicationLifecycleEvents = true, // Auto-capture app lifecycle events (default: true)
79+
CaptureExceptions = true, // Auto-capture unhandled exceptions (default: true)
80+
PersonProfiles = PersonProfiles.IdentifiedOnly, // When to create person profiles
81+
PreloadFeatureFlags = true, // Fetch flags on init (default: true)
82+
SendFeatureFlagEvent = true, // Track flag usage (default: true)
83+
LogLevel = PostHogLogLevel.Warning // Log verbosity (default: Warning)
84+
});
85+
```
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
### Boolean feature flags
2+
3+
```csharp
4+
if (PostHog.IsFeatureEnabled("flag-key"))
5+
{
6+
// Do something differently for this user
7+
}
8+
```
9+
10+
### Multivariate feature flags
11+
12+
```csharp
13+
var flag = PostHog.GetFeatureFlag("flag-key");
14+
if (flag.IsEnabled)
15+
{
16+
string variant = flag.GetVariant("control"); // "control" is the default value
17+
if (variant == "variant-key") // Replace with your variant key
18+
{
19+
// Do something for this variant
20+
}
21+
}
22+
```
23+
24+
### Feature flag payloads
25+
26+
Access payloads through the feature flag object:
27+
28+
```csharp
29+
// Define your payload class (must use [Serializable] and public fields for JsonUtility)
30+
[Serializable]
31+
public class CheckoutConfig
32+
{
33+
public string theme;
34+
public int maxItems;
35+
public bool showBanner;
36+
}
37+
38+
// Get flag and access payload
39+
var flag = PostHog.GetFeatureFlag("checkout-config");
40+
if (flag.IsEnabled)
41+
{
42+
var config = flag.GetPayload<CheckoutConfig>();
43+
Debug.Log($"Theme: {config.theme}, Max items: {config.maxItems}");
44+
}
45+
46+
// For dynamic/nested payloads, use PostHogJson
47+
var payload = flag.GetPayloadJson();
48+
string theme = payload["theme"].GetString("light");
49+
int maxItems = payload["settings"]["maxItems"].GetInt(10);
50+
```
51+
52+
### Ensuring flags are loaded before usage
53+
54+
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.
55+
56+
This means that for most screens, the feature flags are available immediately – **except for the first time a user visits**.
57+
58+
To be notified when flags are loaded:
59+
60+
```csharp
61+
// Via callback during setup
62+
PostHog.Setup(new PostHogConfig
63+
{
64+
ApiKey = "<ph_project_api_key>",
65+
OnFeatureFlagsLoaded = () => Debug.Log("Flags ready!")
66+
});
67+
68+
// Or via event
69+
PostHog.OnFeatureFlagsLoaded += () => UpdateUI();
70+
```
71+
72+
### Reloading feature flags
73+
74+
Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call:
75+
76+
```csharp
77+
await PostHog.ReloadFeatureFlagsAsync();
78+
```
79+
80+
### Overriding server properties for flags
81+
82+
You can set properties used for flag evaluation:
83+
84+
```csharp
85+
// Set person properties for targeting
86+
PostHog.SetPersonPropertiesForFlags(new Dictionary<string, object>
87+
{
88+
{ "plan", "premium" },
89+
{ "beta_user", true }
90+
});
91+
92+
// Set group properties for targeting
93+
PostHog.SetGroupPropertiesForFlags("company", new Dictionary<string, object>
94+
{
95+
{ "size", "enterprise" }
96+
});
97+
98+
// Reset properties
99+
PostHog.ResetPersonPropertiesForFlags();
100+
PostHog.ResetGroupPropertiesForFlags();
101+
```
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import SettingProperties from "./setting-properties-text.mdx"
2+
import NamingTip from "./naming-tip.mdx"
3+
import Intro from "./intro.mdx"
4+
5+
<Intro />
6+
7+
```csharp
8+
PostHog.Capture("user_signed_up");
9+
```
10+
11+
<NamingTip />
12+
13+
<SettingProperties />
14+
15+
```csharp
16+
PostHog.Capture("user_signed_up", new Dictionary<string, object>
17+
{
18+
{ "login_type", "email" },
19+
{ "is_free_trial", true }
20+
});
21+
```
22+
23+
### Capturing screen views
24+
25+
Track screen views to understand user navigation through your game:
26+
27+
```csharp
28+
PostHog.Screen("Main Menu");
29+
30+
// With additional properties
31+
PostHog.Screen("Level Select", new Dictionary<string, object>
32+
{
33+
{ "unlocked_levels", 5 }
34+
});
35+
```

0 commit comments

Comments
 (0)