SDK sample
This sample (with additional methods) is found as part of the Leaderboards SDK package by checking the box to include Samples
when installing from the package manager.
The following example presumes the existence of a leaderboard with the ID my-first-leaderboard
. You can create this from the Unity Cloud Dashboard.
The sample then initializes the Unity services and uses anonymous authentication to sign-in the player in the Awake
lifecycle callback (see SDK Installation & Setup) and then uses the SDK to provide methods for interacting with the leaderboard data and printing it to the console.
C#
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Unity.Services.Authentication;
using Unity.Services.Core;
using Unity.Services.Leaderboards;
using UnityEngine;
public class LeaderboardsSample : MonoBehaviour
{
// Create a leaderboard with this ID in the Unity Cloud Dashboard
const string LeaderboardId = "my-first-leaderboard";
string VersionId { get; set; }
int Offset { get; set; }
int Limit { get; set; }
int RangeLimit { get; set; }
List<string> FriendIds { get; set; }
async void Awake()
{
await UnityServices.InitializeAsync();
await SignInAnonymously();
}
async Task SignInAnonymously()
{
AuthenticationService.Instance.SignedIn += () =>
{
Debug.Log("Signed in as: " + AuthenticationService.Instance.PlayerId);
};
AuthenticationService.Instance.SignInFailed += s =>
{
// Take some action here...
Debug.Log(s);
};
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
public async void AddScore()
{
var scoreResponse = await LeaderboardsService.Instance.AddPlayerScoreAsync(LeaderboardId, 102);
Debug.Log(JsonConvert.SerializeObject(scoreResponse));
}
public async void GetScores()
{
var scoresResponse =
await LeaderboardsService.Instance.GetScoresAsync(LeaderboardId);
Debug.Log(JsonConvert.SerializeObject(scoresResponse));
}
public async void GetPaginatedScores()
{
Offset = 10;
Limit = 10;
var scoresResponse =
await LeaderboardsService.Instance.GetScoresAsync(LeaderboardId, new GetScoresOptions{Offset = Offset, Limit = Limit});
Debug.Log(JsonConvert.SerializeObject(scoresResponse));
}
public async void GetPlayerScore()
{
var scoreResponse =
await LeaderboardsService.Instance.GetPlayerScoreAsync(LeaderboardId);
Debug.Log(JsonConvert.SerializeObject(scoreResponse));
}
public async void GetVersionScores()
{
var versionScoresResponse =
await LeaderboardsService.Instance.GetVersionScoresAsync(LeaderboardId, VersionId);
Debug.Log(JsonConvert.SerializeObject(versionScoresResponse));
}
}