> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cratebytes.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Unity SDK

> Learn about the CrateBytes Unity SDK and how to use it.

# CrateBytes Unity SDK

A comprehensive Unity SDK for integrating CrateBytes backend services into your games. This SDK provides authentication, session management, leaderboards, and player metadata functionality.

## Installation

There are two ways to install the CrateBytes Unity SDK:

### Method 1: Unity Package Manager (Recommended)

1. Open Unity Package Manager (`Window > Package Manager`)
2. Click the **+** button in the top-left corner
3. Select **"Add package from git URL"**
4. Enter the repository URL: `https://github.com/CrateBytes/CrateBytes-UnitySDK.git`
5. Click **Add**

### Method 2: Manual Installation

1. Visit the [CrateBytes Unity SDK GitHub repository](https://github.com/CrateBytes/CrateBytes-UnitySDK)
2. Download the latest release or clone the repository
3. Import the package into your Unity project

### Setup After Installation

1. Add the `CrateBytesSDK` component to a GameObject in your scene
2. Configure the SDK with your project's base URL and public key

## Configuration

### SDK Settings

The SDK can be configured through the Inspector or via code:

```csharp theme={null}
// Configure via code
CrateBytesSDK.Instance.Initialize("https://api.cratebytes.com/api/game", "your-public-key");
```

### Logging

The SDK includes a built-in logging system that can be enabled/disabled:

**Via Inspector:**

* Select the GameObject with the `CrateBytesSDK` component
* Check/uncheck the "Enable Logging" field

**Via Code:**

```csharp theme={null}
// Enable logging
CrateBytesSDK.Instance.enableLogging = true;

// Or use the logger directly
CrateBytesLogger.Enabled = true;

// Disable logging (recommended for production)
CrateBytesLogger.Enabled = false;
```

**Note:** Logging is disabled by default for production builds. Enable only when debugging.

## Quick Start

### 1. Setup

Add the SDK component to your scene:

```csharp theme={null}
// The SDK will automatically create a singleton instance
var sdk = CrateBytesSDK.Instance;

// Configure with your project settings
sdk.Initialize("https://api.cratebytes.com/api/game", "your-public-key");
```

### 2. Authentication

```csharp theme={null}
// Guest authentication
yield return CrateBytesSDK.Instance.Auth.GuestLogin(null, (response) =>
{
    if (response.Success)
    {
        Debug.Log($"Authenticated! Player ID: {response.Data.playerId}");
    }
});

// Steam authentication
yield return CrateBytesSDK.Instance.Auth.SteamLogin("steam-auth-ticket", (response) =>
{
    if (response.Success)
    {
        Debug.Log($"Steam authenticated! Player ID: {response.Data.playerId}");
    }
});
```

### 3. Session Management

```csharp theme={null}
// Start a session
yield return CrateBytesSDK.Instance.Session.StartSession((response) =>
{
    if (response.Success)
    {
        Debug.Log("Session started!");
        // Start automatic heartbeat
        CrateBytesSDK.Instance.StartHeartbeat();
    }
});

// Stop session when done
yield return CrateBytesSDK.Instance.Session.StopSession();
```

### 4. Leaderboards

```csharp theme={null}
// Submit a score
yield return CrateBytesSDK.Instance.Leaderboard.SubmitScore("leaderboard-id", "1000", (response) =>
{
    if (response.Success)
    {
        Debug.Log("Score submitted!");
    }
});

// Get leaderboard entries
yield return CrateBytesSDK.Instance.Leaderboard.GetLeaderboard("leaderboard-id", 1, (response) =>
{
    if (response.Success)
    {
        foreach (var entry in response.Data.entries)
        {
            Debug.Log($"Player {entry.player.playerId}: {entry.score}");
        }
    }
});
```

### 5. Player Metadata

```csharp theme={null}
// Define your player data structure
[Serializable]
public class PlayerData
{
    public int Level { get; set; }
    public int Experience { get; set; }
    public string[] Achievements { get; set; }
}

// Save player data
var playerData = new PlayerData
{
    Level = 5,
    Experience = 1250,
    Achievements = new[] { "FirstWin", "SpeedRunner" }
};

yield return CrateBytesSDK.Instance.Metadata.SetPlayerDataObject(playerData, (response) =>
{
    if (response.Success)
    {
        Debug.Log("Player data saved!");
    }
});

// Retrieve player data
yield return CrateBytesSDK.Instance.Metadata.GetPlayerData<PlayerData>((response) =>
{
    if (response.Success && response.Data != null)
    {
        Debug.Log($"Level: {response.Data.Level}, XP: {response.Data.Experience}");
    }
});
```

## Best Practices

### 1. Session Management

* Always start a session when the player begins playing
* Use automatic heartbeat to keep sessions alive
* Stop sessions when the player stops playing or the app is paused

### 2. Error Handling

* Always check response success before using data
* Implement retry logic for network failures
* Log errors for debugging

### 3. Data Management

* Use strongly-typed data structures for player metadata
* Validate data before sending to the server
* Handle data serialization errors gracefully

### 4. Performance

* Use coroutines for all API calls
* Don't make too many requests simultaneously
* Cache frequently accessed data locally
