GameTribe

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:

SessionExample.cs
using UnityEngine;
using GameTribe.SDK;
public class SessionExample : MonoBehaviour
{
void Start()
{
// Called when SDK is fully initialized
PlatformSDK.Instance.OnSDKReady += OnSDKReady;
// Called when session is authenticated with backend
PlatformSDK.Instance.Session.OnSessionAuthenticated += OnSessionAuthenticated;
// Called if authentication fails
PlatformSDK.Instance.Session.OnSessionAuthenticationFailed += OnAuthFailed;
}
void OnSDKReady()
{
Debug.Log("SDK Ready!");
// Check if session is active
if (PlatformSDK.Instance.Session.IsSessionActive)
{
Debug.Log($"Session ID: {PlatformSDK.Instance.Session.SessionId}");
}
}
void OnSessionAuthenticated(SessionAuthResponse response)
{
Debug.Log("Session authenticated successfully!");
// Access player statistics
var 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:

PropertyTypeDescription
highestScoreintPlayer's best score ever
totalPlaysintNumber of times played
averageScorefloatAverage score across all plays
rankintLeaderboard rank
lastPlayedAtstringISO timestamp of last play
csharp
// Access player stats after authentication
var stats = PlatformSDK.Instance.Session.PlayerStats;
// Display in your UI
highScoreText.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:

csharp
// Optional: Listen for heartbeat failures
PlatformSDK.Instance.Session.OnHeartbeatFailed += (error) =>
{
// Show a connection warning to the player
ShowConnectionWarning();
};
Sessions automatically expire after 24 hours of inactivity or when the player closes the browser tab.

Ending a Session

When gameplay ends, call EndSessionAsync to submit the final score to the leaderboard:

GameOverHandler.cs
public class GameOverHandler : MonoBehaviour
{
public async void OnGameOver(int finalScore)
{
// Submit score and end session
var 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 asynchronously
if (result.scoreRank.HasValue)
{
Debug.Log($"New rank: #{result.scoreRank}");
}
}
else
{
Debug.LogError("Failed to submit score");
}
}
}

End Session Response

PropertyTypeDescription
successboolWhether the submission succeeded
sessionIdstringThe session ID that ended
sessionDurationSecondsintHow long the session lasted
finalScoreintThe score that was submitted
scoreRankint?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
You don't need any tournament-specific code! The backend handles all tournament logic automatically when you call EndSessionAsync orSubmitScore.

Manual Initialization

In rare cases where you need to manually initialize a session (e.g., for testing):

csharp
// Manual initialization with tokens
PlatformSDK.Instance.Session.InitializeWithTokens(
sessionToken: "your-session-token",
userToken: "your-user-jwt-token"
);
// Or let SDK extract from URL (default behavior)
PlatformSDK.Instance.Session.InitializeFromURL();
Manual initialization is only needed for testing. In production, the SDK automatically initializes from URL parameters.

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