# Unity SDK Integration Guide

Source: https://appfig.com/docs/unity-integration

Complete guide to integrating AppFig into your Unity project.

## Installation

> **SDK Download Repository:** [https://github.com/smartconfigui/AppFig-SDKs](https://github.com/smartconfigui/AppFig-SDKs)

**Requirements:** Unity 2021.3+ for the Package Manager install, Unity 2019.4+ with the DLL (supports all platforms: iOS, Android, Windows, macOS, Linux, WebGL)

### Step 1: Add the package

In Unity: **Window > Package Manager > + > Add package from git URL**, then 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.

**That's it!** No additional configuration needed. The SDK works in Mono and IL2CPP builds,
including with Managed Stripping Level set to High.

### Alternative: copy the DLL (older Unity versions)

1. Download `AppFigUnitySDK.dll` from `https://github.com/smartconfigui/AppFig-SDKs/tree/v2.5.0/unity`
2. In Unity, create the folder structure: `Assets/Plugins/AppFig/`
3. Drag `AppFigUnitySDK.dll` into that folder. Unity detects the assembly automatically.

Use one way or the other, not both: two copies of the assembly do not compile.

### What's Included

The single DLL contains all SDK functionality:
- **Core SDK** - `AppFig` class with all feature flag and event methods
- **AppFigHelper** - Optional- MonoBehaviour wrapper for Inspector-based setup
- **AppFigApplier** - Optional- No-code component for applying feature values to GameObjects
- **AppFigABTester** - Optional- Visual A/B testing component

No meta files, no dependencies, no build steps required.

## Quick Start

### Initialize

Initialize with your company credentials:

```csharp
using UnityEngine;

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

        // Log events
        AppFig.LogEvent("app_open");

        // Check features
        if (AppFig.IsFeatureEnabled("double_xp")) {
            ApplyDoubleXP();
        }

        string maxLives = AppFig.GetFeatureValue("max_lives");
        int lives = int.Parse(maxLives);
    }
}
```

## When to Do What: Timing Guide

Understanding WHEN to call each SDK method is crucial for proper implementation. Follow this guide to ensure optimal integration:

| Action | When to Call | Where to Place | Code Example |
|--------|-------------|----------------|--------------|
| **Initialize SDK** | Once at app startup, before any SDK calls | `GameManager.Start()` or `Awake()` | `AppFig.Init(...)` |
| **Log Events** | Immediately after user action | Event handlers, button callbacks | `AppFig.LogEvent("level_complete")` |
| **Set User Properties** | Once at login, when value changes | Auth callback, state change | `AppFig.SetUserProperty("tier", "premium")` |
| **Set Device Properties** | Once at startup (usually auto-detected) | `Start()` method | `AppFig.SetAppVersion("1.0.0")` |
| **Evaluate Features** | Right before you need the value | Decision points, scene load | `AppFig.GetFeatureValue("max_lives")` |
| **Apply Features** | Immediately after evaluation | Same method as evaluation | `if (value) { ShowUI(); }` |
| **Refresh Rules** | On demand or periodically (auto-refresh handles this) | Manual: Settings screen | `AppFig.RefreshRules()` |

### Detailed Timing Scenarios

#### Initialization Timing

```csharp
public class GameManager : MonoBehaviour
{
    void Awake()
    {
        // ✅ CORRECT: Initialize once at startup
        // This ensures SDK is ready before any other code runs
        AppFig.Init("company-id", "tenant-id", "prod", "api-key");
    }

    void Start()
    {
        // ✅ Also acceptable: Initialize in Start()
        // Just ensure it happens before any SDK calls
        AppFig.Init("company-id", "tenant-id", "prod", "api-key");
    }
}

// ❌ WRONG: Don't initialize in every scene
public class LevelManager : MonoBehaviour
{
    void Start()
    {
        AppFig.Init(...); // Bad! SDK already initialized
    }
}

// ❌ WRONG: Don't initialize multiple times
void Update()
{
    AppFig.Init(...); // Bad! Only initialize once
}
```

#### Event Logging Timing

```csharp
// ✅ CORRECT: Log immediately after action
public void OnLevelComplete()
{
    SaveProgress();
    ShowCompletionUI();

    // Log right when it happens
    AppFig.LogEvent("level_complete", new Dictionary<string, string> {
        { "level_number", currentLevel.ToString() },
        { "time_seconds", elapsedTime.ToString() }
    });
}

// ✅ CORRECT: Log on button click
public void OnPurchaseButtonClicked()
{
    // Log the intention immediately
    AppFig.LogEvent("purchase_initiated");

    ShowPurchaseDialog();
}

// ❌ WRONG: Don't batch events
private List<string> pendingEvents = new List<string>();

void OnLevelComplete()
{
    pendingEvents.Add("level_complete"); // Bad! Log immediately
}

void OnApplicationQuit()
{
    // Bad! Events should be logged as they happen
    foreach (var evt in pendingEvents) {
        AppFig.LogEvent(evt);
    }
}

// ❌ WRONG: Don't log in Update()
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        // Bad! Log in the actual event handler
        AppFig.LogEvent("space_pressed");
    }
}
```

#### Property Setting Timing

```csharp
// ✅ CORRECT: Set once when value is established
public void OnLoginSuccess(string userId, string tier)
{
    // Set properties right after authentication
    AppFig.SetUserProperty("user_id", userId);
    AppFig.SetUserProperty("subscription_tier", tier);
    AppFig.SetUserProperty("login_date", DateTime.Now.ToString());
}

// ✅ CORRECT: Update when value changes
public void OnSubscriptionUpgrade(string newTier)
{
    // Update property when it changes
    AppFig.SetUserProperty("subscription_tier", newTier);

    // Re-evaluate features that depend on tier
    UpdateUIBasedOnTier();
}

// ❌ WRONG: Don't set repeatedly with same value
void Update()
{
    // Bad! Set once, not every frame
    AppFig.SetUserProperty("user_id", currentUserId);
}

// ❌ WRONG: Don't set before initialization
void Awake()
{
    AppFig.SetUserProperty("level", "1"); // Bad! Init first

    AppFig.Init(...); // Too late
}
```

#### Feature Evaluation Timing

```csharp
// ✅ CORRECT: Evaluate when you need the value
public void LoadLevel(int levelNumber)
{
    // Check feature right before using it
    string difficultyValue = AppFig.GetFeatureValue("difficulty_multiplier");
    float difficulty = float.Parse(difficultyValue ?? "1.0");

    // Apply immediately
    ApplyDifficultySettings(difficulty);
    LoadScene(levelNumber);
}

// ✅ CORRECT: Cache for performance
private bool hasDoubleXP = false;

void Start()
{
    // Check once and cache the result
    hasDoubleXP = AppFig.IsFeatureEnabled("double_xp");
}

void CalculateXP(int baseXP)
{
    // Use cached value in hot path
    return hasDoubleXP ? baseXP * 2 : baseXP;
}

// ❌ WRONG: Don't check every frame
void Update()
{
    // Bad! Very inefficient
    if (AppFig.IsFeatureEnabled("double_xp"))
    {
        ApplyDoubleXP();
    }
}

// ❌ WRONG: Don't check before logging relevant events
void Start()
{
    // Bad! Feature evaluates to null because no events logged yet
    if (AppFig.IsFeatureEnabled("veteran_bonus")) { }

    // Should log events first
    AppFig.LogEvent("app_open");

    // Now this works
    if (AppFig.IsFeatureEnabled("veteran_bonus")) { }
}
```

#### Feature Application Timing

```csharp
// ✅ CORRECT: Apply immediately after evaluation
void Start()
{
    // Evaluate
    bool showBonus = AppFig.IsFeatureEnabled("welcome_bonus");

    // Apply right away with null handling
    if (showBonus)
    {
        welcomeBonusPanel.SetActive(true);
        GrantCoins(500);
    }
    else
    {
        welcomeBonusPanel.SetActive(false);
    }
}

// ✅ CORRECT: Apply configuration values
void LoadGameSettings()
{
    // Evaluate with fallback
    string maxLivesStr = AppFig.GetFeatureValue("max_lives");
    int maxLives = int.Parse(maxLivesStr ?? "3");

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

// ❌ WRONG: Don't apply in different frame/context
private string featureValue;

void Start()
{
    featureValue = AppFig.GetFeatureValue("theme");
}

void Update()
{
    // Bad! Apply immediately after evaluation
    if (featureValue == "dark")
    {
        ApplyDarkTheme();
    }
}

// ❌ WRONG: Don't forget null handling
void Start()
{
    string maxLives = AppFig.GetFeatureValue("max_lives");

    // Bad! What if maxLives is null?
    int lives = int.Parse(maxLives); // NullReferenceException!

    // Should be:
    int lives = int.Parse(maxLives ?? "3");
}
```

### Complete Lifecycle Example

Here's a complete example showing proper timing for all SDK operations:

```csharp
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

public class GameManager : MonoBehaviour
{
    public GameObject welcomePanel;
    public Text livesText;
    private int playerLives = 3;

    // 1. INITIALIZE: Once at startup
    void Start()
    {
        AppFig.Init("company-id", "tenant-id", "prod", "api-key");

        // 2. SET PROPERTIES: Once when known (device props are auto-detected)
        AppFig.SetAppVersion("1.0.0");

        // 3. TRACK: Log events as they happen
        AppFig.LogEvent("app_open");

        // 4. EVALUATE: When you need values
        CheckWelcomeBonus();
        ConfigureGameSettings();
    }

    void CheckWelcomeBonus()
    {
        // Evaluate right before using
        bool showWelcome = AppFig.IsFeatureEnabled("welcome_bonus");

        // Apply immediately
        if (showWelcome)
        {
            welcomePanel.SetActive(true);
        }
    }

    void ConfigureGameSettings()
    {
        // Evaluate with fallback
        string maxLivesValue = AppFig.GetFeatureValue("max_lives");
        playerLives = int.Parse(maxLivesValue ?? "3");

        // Apply to UI
        livesText.text = $"Lives: {playerLives}";
    }

    public void OnLevelComplete()
    {
        // Track immediately after action
        AppFig.LogEvent("level_complete", new Dictionary<string, string> {
            { "level", currentLevel.ToString() }
        });

        // Re-evaluate features that depend on level completion
        CheckNewUnlocks();
    }

    public void OnSubscriptionPurchased(string tier)
    {
        // Update property when it changes
        AppFig.SetUserProperty("subscription_tier", tier);

        // Re-evaluate features that depend on subscription
        UpdatePremiumFeatures();
    }
}
```

---

## API Reference

### Initialization

```csharp
AppFig.Init(
  string companyId,                    // Required: Your company ID
  string tenantId,                     // Required: Your tenant/project ID
  string env,                          // Required: "dev" or "prod"
  string apiKey,                       // Required: Your API key
  bool autoRefresh = true,             // Optional: Enable auto-refresh (default: true) ✨ NEW DEFAULT
  long pollInterval = 43200000,        // Optional: leave out to follow your plan
  bool debugMode = false,              // Optional: Enable debug logging (default: false) ✨ NEW
  long sessionTimeoutMs = 1800000,     // Optional: 30 minutes (default: 30 min) ✨ NEW
  int maxEvents = 5000,                // Optional: Max events (default: 5000, max: 100000)
  int maxEventAgeDays = 7,             // Optional: Max age in days (default: 7, max: 365)
  string cdnBaseUrl = null             // Optional: rules host (default: production) 🆕 2.3
)
```

**Parameters:**
- `companyId` (required) - Your company ID from AppFig dashboard
- `tenantId` (required) - Your tenant/project ID from AppFig dashboard
- `env` (required) - Environment: `"dev"` or `"prod"`
- `apiKey` (required) - Your API key from AppFig dashboard
- `autoRefresh` (optional) - Enable automatic background rule updates (default: **true**) ⚠️ **Breaking Change**
- `pollInterval` (optional) - Auto-refresh interval in milliseconds. Leave it out and the SDK checks for changes every minute, on every plan 🆕 **New in 2.3**. A value you set is kept, but never faster than your plan allows.
- `debugMode` (optional) - Enable debug logging to Unity console (default: false) 🆕 **New in v2.0**
- `sessionTimeoutMs` (optional) - Session timeout in milliseconds (default: 1800000 = 30 min, range: 60000-7200000) 🆕 **New in v2.0**
- `maxEvents` (optional) - Maximum events to store in PlayerPrefs (100-100000, default: 5000)
- `maxEventAgeDays` (optional) - Maximum age of events in days (1-365, default: 7)
- `cdnBaseUrl` (optional) - The rules host to read from, e.g. `https://rules-stage.appfig.com` for a staging build. Leave it out for production (`https://rules-prod.appfig.com`). Must start with `https://`. 🆕 **New in 2.3**

**Examples:**

```csharp
// Basic initialization (auto-refresh enabled by default)
AppFig.Init("acme-games", "space-shooter", "prod", "sk_live_abc123");

// With a fixed poll interval (1 hour)
AppFig.Init(
    companyId: "acme-games",
    tenantId: "space-shooter",
    env: "prod",
    apiKey: "sk_live_abc123",
    autoRefresh: true,          // Explicit (but this is already the default)
    pollInterval: 3600000       // 1 hour
);

// With debug mode enabled (useful during development)
AppFig.Init(
    companyId: "acme-games",
    tenantId: "space-shooter",
    env: "dev",                 // Use dev environment
    apiKey: "sk_test_abc123",
    autoRefresh: true,
    pollInterval: 600000,       // 10 minutes for faster testing
    debugMode: true             // See all SDK operations in console
);

// With all parameters customized
AppFig.Init(
    companyId: "acme-games",
    tenantId: "space-shooter",
    env: "prod",
    apiKey: "sk_live_abc123",
    autoRefresh: true,
    pollInterval: 3600000,
    debugMode: false,
    sessionTimeoutMs: 900000,   // 15 minutes instead of 30
    maxEvents: 10000,           // Store more events
    maxEventAgeDays: 30         // Keep events for 30 days
);

// Disable auto-refresh (opt-out, manual refresh only)
AppFig.Init(
    companyId: "acme-games",
    tenantId: "space-shooter",
    env: "prod",
    apiKey: "sk_live_abc123",
    autoRefresh: false          // Must call RefreshRules() manually
);
```

### Logging Events

```csharp
AppFig.LogEvent(string eventName)
AppFig.LogEvent(string eventName, Dictionary<string, string> parameters)
```

**Examples:**
```csharp
// Simple event
AppFig.LogEvent("level_complete");

// Event with parameters
AppFig.LogEvent("purchase_made", new Dictionary<string, string> {
    { "item_id", "sword_legendary" },
    { "price", "9.99" },
    { "currency", "USD" }
});

// Screen view (auto-tracked by SDK too)
AppFig.LogScreenView("main_menu", "settings");
```

### Checking Features

```csharp
bool AppFig.IsFeatureEnabled(string featureName)
string AppFig.GetFeatureValue(string featureName)
```

**Examples:**
```csharp
// Boolean check (returns true if value == "on")
if (AppFig.IsFeatureEnabled("new_ui")) {
    LoadNewUI();
} else {
    LoadOldUI();
}

// Get actual value
string maxLives = AppFig.GetFeatureValue("max_lives");
if (maxLives != null) {
    int lives = int.Parse(maxLives);
    playerLives = lives;
}

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

### Setting Properties

```csharp
// User properties
AppFig.SetUserProperty(string key, string value)
AppFig.RemoveUserProperty(string key)

// Device properties
AppFig.SetDeviceProperty(string key, string value)
AppFig.RemoveDeviceProperty(string key)

// App version (convenience method)
AppFig.SetAppVersion(string version)
```

**Examples:**
```csharp
// User properties
AppFig.SetUserProperty("subscription_tier", "premium");
AppFig.SetUserProperty("account_age_days", "30");
AppFig.SetUserProperty("player_level", "15");

// Device properties (most are auto-detected, but you can add custom ones)
AppFig.SetAppVersion("1.2.3");
AppFig.SetDeviceProperty("graphics_quality", "high");

// Remove properties
AppFig.RemoveUserProperty("subscription_tier");
```

### Auto-Detected Device Properties

These are automatically set by the SDK on initialization:

```
platform          "iOS", "Android", "Windows", "macOS", "Linux", etc.
os_version        "17.0", "13", "11.0"
language          "English", "Japanese", "Spanish"
timezone          "America/Los_Angeles", "Asia/Tokyo"
country           "US", "JP", "GB" (requires internet on first run)
device_brand      "Apple", "Samsung", "Google", "Huawei"
device_model      "iPhone 15", "Galaxy S23", "Pixel 8"
```

Use these in your rules without any setup!

### Session Tracking

Automatically tracked:

```csharp
// These events are logged automatically:
"first_open"     // First time app opens (persisted in PlayerPrefs)
"session_start"  // App gains focus
"session_end"    // App loses focus or 10 minutes of inactivity
"screen_view"    // When you call LogScreenView()
```

### Manual Refresh

```csharp
AppFig.RefreshRules()  // Manually reload rules from CDN
```

**Example:**
```csharp
// Manually refresh rules (useful for testing rule changes)
AppFig.RefreshRules();
```

**Note:** `SetAutoRefresh()` and `SetPollInterval()` are deprecated. Use the `autoRefresh` and `pollInterval` parameters in `Init()` instead.

### Feature Reset (Recurring Triggers)

```csharp
AppFig.ResetFeature(string featureName)
AppFig.ResetAllFeatures()
```

Reset a feature's cached value and force re-evaluation. Useful for implementing recurring triggers like "show popup every 3 events".

**Example:**
```csharp
// Check if feature is enabled
if (AppFig.IsFeatureEnabled("level_complete_popup")) {
    ShowPopup("You've completed 3 levels!");

    // Reset so it triggers again after next 3 events
    AppFig.ResetFeature("level_complete_popup");
}

// With event logging
void OnLevelComplete(int level) {
    AppFig.LogEvent("level_complete", new Dictionary<string, string> {
        { "level", level.ToString() }
    });

    // Check for milestone reward
    if (AppFig.IsFeatureEnabled("milestone_reward")) {
        ShowReward();
        AppFig.ResetFeature("milestone_reward");
    }
}
```

**Use Cases:**
- Show popup every N events (e.g., every 3 level completions)
- Recurring promotions after X purchases
- Periodic reward unlocks
- Time-based feature re-triggers

See [Feature Reset Guide](../../SDKs/FEATURE_RESET_GUIDE.md) for detailed examples.

### Debugging

```csharp
AppFig.GetDebugInfo()  // Returns dict with rules, events, properties, cache
```

**Example:**
```csharp
var debug = AppFig.GetDebugInfo();
Debug.Log($"Rules loaded: {debug.rules.Count}");
Debug.Log($"Events logged: {debug.events.Count}");
Debug.Log($"User properties: {debug.userProperties.Count}");
Debug.Log($"Cached features: {debug.cachedResults.Count}");
```

## Using AppFigHelper (Optional)

`AppFigHelper` is a MonoBehaviour that makes initialization easier with Inspector setup.

### Setup

1. Create an empty GameObject in your first scene
2. Add `AppFigHelper` component
3. Configure in Inspector:

- Company ID: `your-company-id`
- Tenant ID: `your-tenant-id`
- Environment: `prod` or `dev`
- API Key: `your-api-key`
- Enable Debug Logs: ☑ (optional)

### Usage

```csharp
// Access anywhere via singleton
AppFigHelper.Instance.LogEvent("button_clicked");

string value = AppFigHelper.Instance.GetFeatureValue("max_lives");

if (AppFigHelper.Instance.IsFeatureEnabled("double_xp")) {
    ApplyDoubleXP();
}
```

### No-Code Event Logging with Unity UI

You can connect AppFigHelper methods directly to Unity UI components without writing any code!

#### Button onClick Events

**Setup:**
1. Select your Button in the scene
2. In the Inspector, find the **OnClick()** section
3. Click the **+** button to add a new event
4. Drag your AppFigHelper GameObject into the object field
5. Select **AppFigHelper** → **LogEvent(string)**
6. Enter your event name (e.g., "button_clicked")

**Example:**
```
GameObject: PlayButton
Component: Button
  OnClick():
    - AppFigHelper.LogEvent("play_button_clicked")

GameObject: SettingsButton
Component: Button
  OnClick():
    - AppFigHelper.LogEvent("settings_opened")
```

#### Tracking Multiple Interactions

You can add multiple AppFigHelper calls to a single button:

```
GameObject: PurchaseButton
Component: Button
  OnClick():
    - AppFigHelper.LogEvent("purchase_initiated")
    - AppFigHelper.SetUserProperty("last_purchase_attempt", "now")
    - PurchaseManager.ProcessPurchase()  // Your custom method
```

#### Dropdown onChange Events

Track dropdown selections:

```
GameObject: DifficultyDropdown
Component: Dropdown
  OnValueChanged():
    - AppFigHelper.LogEvent("difficulty_changed")
```

#### Toggle onValueChanged Events

Track toggle switches:

```
GameObject: SoundToggle
Component: Toggle
  OnValueChanged():
    - AppFigHelper.LogEvent("sound_toggled")
```

#### Slider onValueChanged Events

Track slider adjustments:

```
GameObject: VolumeSlider
Component: Slider
  OnValueChanged():
    - AppFigHelper.LogEvent("volume_adjusted")
```

**Benefits:**
- Zero code required for basic event logging
- Quick prototyping and testing
- Perfect for designers and non-programmers
- Can be combined with custom scripts

**Note:** For events with parameters, you'll still need to write a simple wrapper method. See [Logging Events](#logging-events) above.

## Visual Components (No Code!)

### AppFigApplier

Apply feature values to GameObjects without writing code.

**Use cases:**
- Show/hide objects based on features
- Update text with feature values
- Set numeric values (light intensity, volume, speed)

**Setup:**
1. Add `AppFigApplier` component to any GameObject
2. Set Feature Name (e.g., "show_bonus_ui")
3. Choose Apply Type:
   - **Enable/Disable**: Show/hide the GameObject
   - **Text Content**: Update Text/TextMeshPro component
   - **Numeric Value**: Set float value on component (volume, intensity, etc.)

**Example:**
```
GameObject: BonusPanel
Component: AppFigApplier
  - Feature Name: "bonus_panel"
  - Apply Type: Enable/Disable

Rule: IF user completed 10+ levels THEN "bonus_panel" = "on"
Result: BonusPanel appears after 10 level completions
```

### AppFigABTester

A/B test visual elements with unlimited variants.

**Use cases:**
- Test different button colors
- Swap sprites/materials
- Try different prefabs
- Experiment with audio

**Setup:**
1. Add `AppFigABTester` component to any GameObject
2. Set Feature Name (e.g., "button_color")
3. Choose Component Type (Sprite, Material, Color, Prefab, AudioClip)
4. Define variants with feature values

**Example:**
```
GameObject: UpgradeButton
Component: AppFigABTester
  - Feature Name: "button_color"
  - Component Type: Color (Image)
  - Variants:
    * Feature Value: "red" → Color: #FF0000
    * Feature Value: "blue" → Color: #0000FF
    * Feature Value: "green" → Color: #00FF00

Rule: IF user from US THEN "button_color" = "red"
Rule: IF user from EU THEN "button_color" = "blue"
```

## Best Practices

### 1. Initialize Early

Initialize in your first scene's `Start()` or `Awake()`:

```csharp
void Awake()
{
    AppFig.Init("company", "tenant", "prod", "api-key");
}
```

### 2. Cache Feature Values

Don't check the same feature repeatedly:

```csharp
// ❌ Bad: Checks every frame
void Update() {
    if (AppFig.IsFeatureEnabled("double_xp")) {
        // ...
    }
}

// ✅ Good: Check once, store result
private bool hasDoubleXP;

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

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

### 3. Handle Null Values

Always check for null:

```csharp
string maxLives = AppFig.GetFeatureValue("max_lives");
if (maxLives != null) {
    int lives = int.Parse(maxLives);
} else {
    int lives = 5; // Default fallback
}
```

### 4. Log Events Liberally

The more events you log, the more powerful your targeting:

```csharp
void CompleteLevel() {
    AppFig.LogEvent("level_complete", new Dictionary<string, string> {
        { "level_number", currentLevel.ToString() },
        { "time_seconds", timeElapsed.ToString() },
        { "stars", starsEarned.ToString() }
    });
}
```

### 5. Use Meaningful Event Parameters

```csharp
// ✅ Good: Descriptive parameters
AppFig.LogEvent("purchase_made", new Dictionary<string, string> {
    { "item_id", "legendary_sword" },
    { "price_usd", "9.99" },
    { "payment_method", "credit_card" }
});

// ❌ Bad: Vague parameters
AppFig.LogEvent("purchase_made", new Dictionary<string, string> {
    { "id", "123" },
    { "amt", "999" }
});
```

## Troubleshooting

### DLL not recognized by Unity

**Problem:** Unity doesn't detect the DLL or shows import errors

**Solutions:**
1. Verify `AppFigUnitySDK.dll` is in `Assets/Plugins/AppFig/` folder
2. Check the Inspector for the DLL - it should show "Plugin" as the type
3. Right-click in Project window and select "Refresh" to force Unity to re-import
4. If still not working, restart Unity Editor

### "The type or namespace name 'AppFig' could not be found"

**Problem:** Scripts can't find AppFig classes

**Solutions:**
1. Verify the DLL is properly imported (check Plugin Inspector)
2. Try reimporting: Right-click DLL → Reimport
3. Check Unity console for import errors or warnings
4. Ensure you're using Unity 2019.4 or higher (minimum supported version)

### "AppFig not initialized"

**Problem:** Calling SDK methods before `Init()`

**Solution:**
```csharp
void Start() {
    AppFig.Init(...);  // Must be first!
    AppFig.LogEvent("app_open");  // Now OK
}
```

### Feature always returns null

**Problem:** No rules match for this feature

**Solutions:**
1. Check feature name spelling (case-sensitive)
2. Verify rules are loaded: Check console for `[AppFig] ✅ Loaded X rule(s)`
3. Log relevant events/properties before checking feature
4. Enable debug logs to see rule evaluation

### Rules not updating

**Problem:** Changes in dashboard not reflected in app

**Solutions:**
1. Wait until auto-refresh interval passes
2. Call `AppFig.RefreshRules()` manually
3. Check console for `[AppFig] 🔄 Auto-refresh` messages
4. Verify internet connection

## Performance Tips

### Event History Management

The SDK automatically manages event history to maintain optimal performance without manual intervention.

### Memory and CPU Usage

AppFig has minimal memory and CPU overhead, making it suitable for production Unity applications across all platforms including mobile devices. The SDK is optimized for:

- Low memory footprint
- Fast feature checks with intelligent caching
- Efficient rule evaluation

While it's safe to check features frequently, we recommend caching feature values when possible to follow best practices.

## Next Steps

- **[Rule Schema](https://appfig.com/docs/rule-schema)** - All rule options
- **[Testing Guide](https://appfig.com/docs/testing)** - Test your features
