A comprehensive Unity SDK for integrating CrateBytes backend services into your games. This SDK provides authentication, session management, leaderboards, and player metadata functionality.
- Authentication: Guest and Steam authentication support
- Session Management: Automatic session tracking with heartbeat
- Leaderboards: Submit scores and retrieve leaderboard data
- Player Metadata: Store and retrieve player-specific data
- Unity Integration: Built specifically for Unity with coroutine support
- Error Handling: Comprehensive error handling and logging
- Import the CrateBytes SDK package into your Unity project
- Add the
CrateBytesSDK
component to a GameObject in your scene - Configure the SDK with your project's base URL and public key
The SDK can be configured through the Inspector or via code:
// Configure via code
CrateBytesSDK.Instance.Initialize("https://api.cratebytes.com/api/game", "your-public-key");
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:
// 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.
Add the SDK component to your scene:
// 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");
// 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}");
}
});
// 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();
// 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}");
}
}
});
// 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}");
}
});
Main SDK class that manages all services.
Auth
: Authentication serviceSession
: Session management serviceLeaderboard
: Leaderboard serviceMetadata
: Player metadata service
Initialize(string baseUrl, string publicKey)
: Configure the SDKIsConfigured()
: Check if SDK is properly configuredStartHeartbeat()
: Start automatic session heartbeatStopHeartbeat()
: Stop automatic session heartbeat
Handles user authentication.
GuestLogin(string playerId, Action<CrateBytesResponse<AuthResponse>> callback)
: Authenticate as guestSteamLogin(string steamAuthTicket, Action<CrateBytesResponse<AuthResponse>> callback)
: Authenticate with SteamIsAuthenticated()
: Check if user is authenticatedGetAuthToken()
: Get current auth tokenLogout()
: Clear authentication
Manages player sessions.
StartSession(Action<CrateBytesResponse<SessionData>> callback)
: Start a new sessionHeartbeat(Action<CrateBytesResponse<SessionData>> callback)
: Send heartbeatStopSession(Action<CrateBytesResponse<SessionData>> callback)
: Stop current sessionIsSessionActive()
: Check if session is activeGetCurrentSession()
: Get current session data
Handles leaderboard operations.
GetLeaderboard(string leaderboardId, int page, Action<CrateBytesResponse<LeaderboardResponse>> callback)
: Get leaderboard entriesSubmitScore(string leaderboardId, string score, Action<CrateBytesResponse<ScoreSubmissionResponse>> callback)
: Submit a score
Manages player data.
GetPlayerData(Action<CrateBytesResponse<PlayerDataResponse>> callback)
: Get current player dataGetPlayerDataBySequentialId(int sequentialId, Action<CrateBytesResponse<PlayerDataResponse>> callback)
: Get player data by IDSetPlayerData(string data, Action<CrateBytesResponse<PlayerDataResponse>> callback)
: Set player data as stringSetPlayerDataObject(object data, Action<CrateBytesResponse<PlayerDataResponse>> callback)
: Set player data as objectDeletePlayerData(Action<CrateBytesResponse<string>> callback)
: Delete player dataGetPlayerData<T>(Action<CrateBytesResponse<T>> callback)
: Get player data as specific type
public class AuthResponse
{
public string token { get; set; }
public string playerId { get; set; }
public int sequentialId { get; set; }
public string steamId { get; set; }
}
public class SessionData
{
public string id { get; set; }
public string playerId { get; set; }
public DateTime startTime { get; set; }
public DateTime lastHeartbeat { get; set; }
public DateTime? endTime { get; set; }
}
public class LeaderboardResponse
{
public LeaderboardInfo leaderboard { get; set; }
public LeaderboardEntry[] entries { get; set; }
public int totalEntries { get; set; }
public int pages { get; set; }
}
All API calls return a CrateBytesResponse<T>
object with the following structure:
public class CrateBytesResponse<T>
{
public int StatusCode { get; set; }
public T Data { get; set; }
public CrateBytesError Error { get; set; }
public bool Success { get; set; }
}
Always check the Success
property before using the Data
:
yield return CrateBytesSDK.Instance.Auth.GuestLogin(null, (response) =>
{
if (response.Success)
{
// Use response.Data safely
Debug.Log($"Player ID: {response.Data.playerId}");
}
else
{
// Handle error
Debug.LogError($"Error: {response.Error?.Message}");
}
});
- 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
- Always check response success before using data
- Implement retry logic for network failures
- Log errors for debugging
- Use strongly-typed data structures for player metadata
- Validate data before sending to the server
- Handle data serialization errors gracefully
- Use coroutines for all API calls
- Don't make too many requests simultaneously
- Cache frequently accessed data locally
Configure the SDK in the Unity Inspector or programmatically:
// Inspector configuration
[SerializeField] private string baseUrl = "https://api.cratebytes.com/api/game";
[SerializeField] private string publicKey = "your-public-key";
[SerializeField] private float heartbeatInterval = 60f; // 1 minute
[SerializeField] private float sessionTimeout = 300f; // 5 minutes
// Programmatic configuration
CrateBytesSDK.Instance.Initialize(baseUrl, publicKey);
- Unity 2020.3 or later
- Newtonsoft.Json (included in package)
For support and documentation, visit:
- Documentation: https://docs.cratebytes.com
- Website: https://cratebytes.com
- Email: support@cratebytes.com
This SDK is provided by CrateBytes for integration with the CrateBytes backend service.