Unity SDK sample
Refer to sample code that implements Leaderboards functionality in a Unity project.
Read time 1 minuteLast updated 8 months ago
This sample (with additional methods) is found as part of the Leaderboards SDK package by checking the box to include when installing from the package manager.
SamplesThe following example presumes the existence of a leaderboard with the ID . You can create this from the Unity Dashboard.
my-first-leaderboardThe sample then initializes the Unity services and uses anonymous authentication to sign-in the player in the 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.
Awakeusing 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 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)); }}