Unity SDK sample
Refer to sample code that implements Leaderboards functionality in a Unity project.
Read time 1 minuteLast updated 22 days ago
This sample (with additional methods) is found as part of the Leaderboards SDK package by checking the box to include
Samplesmy-first-leaderboardAwakeusing 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)); }}