# Feature flags in Unity: a step-by-step setup

Source: https://appfig.com/guides/feature-flags-in-unity

Add the AppFig package from a git URL, call AppFig.Init once, then read flags with IsFeatureEnabled and GetFeatureValue. Rules run on the device.

To add feature flags to a Unity game, install a flag SDK, initialize it once at startup, and replace the `if` you want to control with a lookup that has a fallback. With AppFig that is one package from a git URL, one `AppFig.Init` call, and `AppFig.IsFeatureEnabled("name")` wherever the decision is made; rules are evaluated on the device, so a check costs no network call and works offline.

This guide goes from an empty project to a flag that targets players by what they have done in the game.

## Step 1: Install the package

Requirements: Unity 2021.3 or later for the Package Manager install.

In Unity, open **Window > Package Manager > + > Add package from git URL** and enter:

```
https://github.com/smartconfigui/AppFig-SDKs.git?path=/unity#v2.5.0
```

The tag at the end pins the version; change it to update. The same address works as a line in `Packages/manifest.json` under the name `com.appfig.sdk`. Nothing else needs configuring, and the SDK works in Mono and IL2CPP builds, including with Managed Stripping Level set to High.

On Unity 2019.4 to 2021.2, download `AppFigUnitySDK.dll` from the [SDK repository](https://github.com/smartconfigui/AppFig-SDKs/tree/v2.5.0/unity) and drag it into `Assets/Plugins/AppFig/`. Use one way or the other, not both: two copies of the assembly do not compile. Details are in [Installing the SDKs](/docs/package-manager-setup).

## Step 2: Initialize once at startup

Call `Init` in the first scene, before any other SDK call, with the ids and API key from the AppFig dashboard:

```csharp
using UnityEngine;

public class GameManager : MonoBehaviour
{
    void Awake()
    {
        AppFig.Init(
            companyId: "your-company-id",
            tenantId: "your-tenant-id",
            env: "prod",              // "dev" or "prod"
            apiKey: "your-api-key"
        );
    }
}
```

Do not call it again in later scenes. During development, add `debugMode: true` to see what the SDK does in the Console.

If you prefer the Inspector, add the `AppFigHelper` component to an empty GameObject in the first scene and fill in the same four fields there.

## Step 3: Your first flag

In the dashboard, create a feature called `double_xp` with one rule that has no conditions and the value `on`, then publish. In the game:

```csharp
if (AppFig.IsFeatureEnabled("double_xp")) {
    ApplyDoubleXP();
}
```

`IsFeatureEnabled` returns `true` when the feature's value is `"on"`. For anything else, including no matching rule, it returns `false`, so the "off" branch is your default.

To switch the flag off, change the value and publish. The SDK checks for changes every minute by default while the game is in the foreground, so there is nothing to ship.

## Step 4: Read a value with a fallback

A flag does not have to be a switch. A value is one switch, number or text, stored as a string, and you parse it:

```csharp
void LoadGameSettings()
{
    // Evaluate with fallback
    string maxLivesStr = AppFig.GetFeatureValue("max_lives");
    int maxLives = int.Parse(maxLivesStr ?? "3");

    // Apply to game state
    playerMaxLives = maxLives;
    UpdateUI();
}
```

`GetFeatureValue` returns `null` when no rule matches or when rules have not loaded yet. Without the `?? "3"`, `int.Parse` throws on that `null`. Make the fallback the value the game uses today, so nothing changes until you publish a rule.

## Step 5: Log events and set properties

Flags become more useful when rules can see what the player does. Log events when they happen:

```csharp
public void OnLevelComplete()
{
    AppFig.LogEvent("level_complete", new Dictionary<string, string> {
        { "level_number", currentLevel.ToString() },
        { "time_seconds", elapsedTime.ToString() }
    });
}
```

And set user properties when a value is known or changes:

```csharp
AppFig.SetUserProperty("subscription_tier", "premium");
```

Device properties (`platform`, `os_version`, `language`, `timezone`, `country`, `device_brand`, `device_model`) are detected by the SDK. `first_open`, `session_start` and `session_end` are logged for you.

For simple cases you can skip the code: in a Button's **OnClick()** list, drag in the `AppFigHelper` GameObject and choose **AppFigHelper → LogEvent(string)**.

## Step 6: A rule that targets by player behavior

Suppose a veteran bonus should go to players who completed at least 10 levels in the last week and are not subscribers. The rule for the `veteran_bonus` feature looks like this:

```json
{
  "veteran_bonus": [
    {
      "conditions": {
        "events": {
          "mode": "simple",
          "operator": "AND",
          "items": [
            {
              "key": "level_complete",
              "count": { "operator": ">=", "value": 10 },
              "within_last_days": 7
            }
          ]
        },
        "user_properties": [
          {
            "key": "subscription_tier",
            "value": { "operator": "!=", "value": "premium" }
          }
        ],
        "user_properties_operator": "AND",
        "device": [],
        "device_operator": "AND"
      },
      "value": "2x"
    }
  ]
}
```

You build this in the dashboard's rule builder; the JSON is what the SDK downloads. Events, user properties and device conditions must all pass for a rule to match. A feature can have several rules, checked top to bottom, and the first match wins ([rule prioritization](/docs/rule-prioritization)). Events can also be matched as a sequence, such as `tutorial_start` followed by `tutorial_complete`; see the [rule schema](/docs/rule-schema).

Because the rule runs on the device against events the game just logged, the player gets the bonus when the tenth level is completed, not after a server has caught up. Read the value after the event:

```csharp
string bonus = AppFig.GetFeatureValue("veteran_bonus");
if (bonus == null) {
    Debug.Log("No bonus active");
} else {
    ApplyBonus(bonus); // "2x", "1.5x", etc.
}
```

One ordering detail from the docs: check a behavior-based flag after you have logged the events it depends on, not before.

## What happens when the player is offline?

Rules are downloaded from a CDN, cached on the device and evaluated locally, so a flag check never waits for the network and keeps working with no connection. Events are stored in PlayerPrefs (5,000 events and 7 days by default, both adjustable in `Init` with `maxEvents` and `maxEventAgeDays`), so behavior rules keep matching between sessions.

The case to plan for is a first launch with no connection: there are no rules yet, lookups return `null`, and your fallbacks decide. `country` also needs internet on the first run.

## Performance tips

The SDK caches feature values after evaluation and has low memory and CPU overhead. The docs still recommend three habits:

- **Do not check flags in `Update()`.** Check once and store the result:

```csharp
private bool hasDoubleXP;

void Start() {
    hasDoubleXP = AppFig.IsFeatureEnabled("double_xp");
}

void Update() {
    if (hasDoubleXP) {
        // ...
    }
}
```

- **Evaluate right before you need the value,** such as at scene load or a decision point, and apply it in the same method.
- **Log events in the handler where they happen,** not batched at quit and not from `Update()`.

## Testing a flag

`AppFig.GetDebugInfo()` shows what the SDK holds:

```csharp
var debug = AppFig.GetDebugInfo();
Debug.Log($"Rules loaded: {debug.rules.Count}");
Debug.Log($"Events logged: {debug.events.Count}");
```

If a feature always returns `null`, check the spelling (names are case-sensitive), confirm the Console shows `[AppFig] ✅ Loaded X rule(s)`, and make sure the events the rule needs were logged first. `AppFig.RefreshRules()` reloads rules on demand. The [testing guide](/docs/testing) has more.

## Where to go next

- Turn a rule's value into a split test with the dashboard's A/B toggle, or run an [experiment](/docs/experiments) across several values. A worked case is in [How to A/B test level difficulty](/guides/ab-test-game-difficulty).
- Let the [guided setup](/docs/guided-setup) scan the project and open a pull request that installs the SDK and reads the values you pick.
- For the term itself, see the [feature flag glossary entry](/glossary/feature-flag).

## FAQ

### Do feature flags slow down a Unity game?

A check is a local lookup with no network call, and the SDK caches values after evaluation. Keep checks out of `Update()` and store the result in a field, as the docs recommend.

### What does a flag return before rules have loaded?

`GetFeatureValue` returns `null` and `IsFeatureEnabled` returns `false`. Give every lookup a fallback equal to the game's current behavior, so a first launch without a connection plays exactly as before.

### Does AppFig work with IL2CPP and code stripping?

Yes. The SDK works in Mono and IL2CPP builds, including with Managed Stripping Level set to High.

### How fast does a flag change reach players?

The SDK checks for changes every minute by default while the game is in the foreground. You can set `pollInterval` in `Init`, or call `AppFig.RefreshRules()` to reload on demand.

### What does it cost?

The Lite plan is free for one app with 5 configs and one A/B test at a time. The Full plan is $99 per app a month and is never priced per user or per fetch; see [pricing](/#pricing).
