Session Management
Handle player authentication, sessions, and score submission.
Overview
The GameTribe SDK manages player sessions automatically. When a player starts your game from the GameTribe platform, the SDK authenticates them and tracks their gameplay session.
Sessions enable leaderboards, tournaments, and player statistics. The SDK handles all the complexity of session lifecycle management for you.
How Sessions Work
Here's the session lifecycle:
- Initialization — SDK extracts session and user tokens from the URL
- Authentication — SDK authenticates with the backend and activates the session
- Heartbeat — SDK sends heartbeats every 30 seconds to keep the session alive
- End Session — When gameplay ends, submit the final score
Session Authentication
The SDK automatically extracts tokens from the URL when running on GameTribe. You can listen for authentication events:
using UnityEngine;using GameTribe.SDK;public class SessionExample : MonoBehaviour{void Start(){// Called when SDK is fully initializedPlatformSDK.Instance.OnSDKReady += OnSDKReady;// Called when session is authenticated with backendPlatformSDK.Instance.Session.OnSessionAuthenticated += OnSessionAuthenticated;// Called if authentication failsPlatformSDK.Instance.Session.OnSessionAuthenticationFailed += OnAuthFailed;}void OnSDKReady(){Debug.Log("SDK Ready!");// Check if session is activeif (PlatformSDK.Instance.Session.IsSessionActive){Debug.Log($"Session ID: {PlatformSDK.Instance.Session.SessionId}");}}void OnSessionAuthenticated(SessionAuthResponse response){Debug.Log("Session authenticated successfully!");// Access player statisticsvar stats = response.playerStats;Debug.Log($"High Score: {stats.highestScore}");Debug.Log($"Total Plays: {stats.totalPlays}");Debug.Log($"Rank: #{stats.rank}");Debug.Log($"Average Score: {stats.averageScore}");}void OnAuthFailed(string error){Debug.LogError($"Session authentication failed: {error}");}}
Player Statistics
After authentication, you have access to the player's statistics:
| Property | Type | Description |
|---|---|---|
| highestScore | int | Player's best score ever |
| totalPlays | int | Number of times played |
| averageScore | float | Average score across all plays |
| rank | int | Leaderboard rank |
| lastPlayedAt | string | ISO timestamp of last play |
// Access player stats after authenticationvar stats = PlatformSDK.Instance.Session.PlayerStats;// Display in your UIhighScoreText.text = $"Best: {stats.highestScore}";rankText.text = $"Rank: #{stats.rank}";playsText.text = $"Plays: {stats.totalPlays}";
Session Heartbeat
The SDK automatically sends heartbeat signals every 30 seconds to keep the session alive. You don't need to do anything — it's handled automatically.
If heartbeats fail, the SDK will retry with exponential backoff. You can listen for failures if you want to show a connection warning:
// Optional: Listen for heartbeat failuresPlatformSDK.Instance.Session.OnHeartbeatFailed += (error) =>{// Show a connection warning to the playerShowConnectionWarning();};
Ending a Session
When gameplay ends, call EndSessionAsync to submit the final score to the leaderboard:
public class GameOverHandler : MonoBehaviour{public async void OnGameOver(int finalScore){// Submit score and end sessionvar result = await PlatformSDK.Instance.Session.EndSessionAsync(finalScore,new Dictionary<string, object>{{ "level", currentLevel },{ "difficulty", "hard" },{ "completionTime", gameTime }});if (result.success){Debug.Log($"Score submitted: {result.finalScore}");Debug.Log($"Session duration: {result.sessionDurationSeconds}s");// Note: scoreRank may be null as it's computed asynchronouslyif (result.scoreRank.HasValue){Debug.Log($"New rank: #{result.scoreRank}");}}else{Debug.LogError("Failed to submit score");}}}
End Session Response
| Property | Type | Description |
|---|---|---|
| success | bool | Whether the submission succeeded |
| sessionId | string | The session ID that ended |
| sessionDurationSeconds | int | How long the session lasted |
| finalScore | int | The score that was submitted |
| scoreRank | int? | New leaderboard rank (may be null) |
Tournament Integration
The SDK automatically handles tournament participation. When a tournament is active:
- Players are automatically enrolled when they submit scores
- Scores accumulate across the tournament duration
- Anti-cheat validation is applied automatically
EndSessionAsync orSubmitScore.Manual Initialization
In rare cases where you need to manually initialize a session (e.g., for testing):
// Manual initialization with tokensPlatformSDK.Instance.Session.InitializeWithTokens(sessionToken: "your-session-token",userToken: "your-user-jwt-token");// Or let SDK extract from URL (default behavior)PlatformSDK.Instance.Session.InitializeFromURL();
Best Practices
- Wait for OnSDKReady — Don't start gameplay until the SDK is ready
- Check IsSessionActive — Verify the session is active before allowing gameplay
- Always call EndSessionAsync — Submit scores even if the player quits early
- Handle auth failures gracefully — Show a retry option or offline mode
- Display player stats — Show high score and rank to increase engagement