Guide · Unity 2021.3+
Add an online leaderboard to a Unity game
Give your Unity game a global high-score table in about ten minutes, with no server of your own. Players don't need an account: each one is an anonymous player remembered on their device.
By the end, your game-over scene saves the score, tells the player their all-time rank and shows the top 10, with their own row marked. It works on desktop, mobile and WebGL.
1. Set up the leaderboard
- Sign in to the dashboard with GitHub or Google and create an app for your game. The free plan covers 10,000 scores a month.
- Under API keys, create a publishable key (
lb_pk_…). It's safe to ship in the game. - Under Metrics, create
highscorewith the aggregationmax, so each player keeps their best run. - Under Leaderboards, create
alltimeonhighscore, ranked highest first. - WebGL only: under Allowed origins, add the origin you'll publish to, such as your itch.io or own domain. Desktop and mobile builds send no origin and need nothing here.
2. Install the package
In Window › Package Manager, click + › Add package from git URL and enter:
https://github.com/Uluru-Solutions/oneleader-unity.git
It also installs Unity's Newtonsoft JSON package. The README lists every call.
3. Add a leaderboard helper
Save this as Assets/Scripts/Leaderboard.cs and paste in your publishable key. It creates the anonymous player on the first run and saves it in PlayerPrefs. If the leaderboard can't be reached (offline, over quota, rate limited) it logs a warning and returns null, so the game carries on.
using System.Threading.Tasks;
using OneLeader;
using UnityEngine;
// The leaderboard is a bonus: offline, over quota or rate limited, the game carries on without it.
public static class Leaderboard
{
static OneLeaderClient client;
static OneLeaderClient Client => client ??= new OneLeaderClient("lb_pk_...");
/// <summary>Records a finished run. Returns the player's all-time rank (by their best score), or null if it couldn't be saved.</summary>
public static async Task<int?> SubmitRun(double score)
{
try
{
if (Client.Session == null) await Client.StartSession();
var receipt = await Client.SubmitScore("highscore", score);
return receipt.Leaderboards.Find(b => b.Key == "alltime")?.Rank;
}
catch (OneLeaderException e) { Debug.LogWarning($"Leaderboard: {e.Message} ({e.Status})"); return null; }
}
/// <summary>The top 10, plus the player's own row in User even when they're further down. Null if it couldn't be read.</summary>
public static async Task<LeaderboardPage> TopTen()
{
try { return await Client.GetLeaderboard("alltime", limit: 10); }
catch (OneLeaderException e) { Debug.LogWarning($"Leaderboard: {e.Message} ({e.Status})"); return null; }
}
public static async Task<bool> SetName(string name)
{
try { await Client.SetDisplayName(name); return true; }
catch (OneLeaderException e) { Debug.LogWarning($"Leaderboard: {e.Message} ({e.Status})"); return false; }
}
}
4. Show it on game over
Save this as Assets/Scripts/GameOver.cs:
using System.Linq;
using System.Threading.Tasks;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
// Shows the score, the player's rank and the top 10. From your game scene, when a run ends:
// GameOver.Score = score; SceneManager.LoadScene("GameOver");
public class GameOver : MonoBehaviour
{
public static double Score;
public TMP_Text scoreText, statusText, boardText;
public TMP_InputField nameInput;
public Button playAgain;
async void Start()
{
boardText.richText = false; // players choose their names: never read them as markup
nameInput.gameObject.SetActive(false);
nameInput.onSubmit.AddListener(SaveName);
playAgain.onClick.AddListener(() => SceneManager.LoadScene("Game"));
scoreText.text = $"Score: {Score}";
statusText.text = "Saving your score…";
var rank = await Leaderboard.SubmitRun(Score);
if (this == null) return; // the player left before the board loaded
statusText.text = rank != null ? $"Your best is #{rank} all time" : "Leaderboard unavailable right now";
await ShowBoard();
}
async Task ShowBoard()
{
var page = await Leaderboard.TopTen();
if (this == null || page == null) return;
var me = page.User;
boardText.text = string.Join("\n", page.Rankings.Select(row =>
$"{row.Rank}. {row.DisplayName ?? "Anonymous"} {row.Value}{(row.PlayerId == me?.PlayerId ? " ← you" : "")}"));
// First run: the player has no name yet, so ask for one.
nameInput.gameObject.SetActive(me != null && me.DisplayName == null);
}
async void SaveName(string name)
{
nameInput.gameObject.SetActive(false);
if (name.Trim() != "" && await Leaderboard.SetName(name.Trim()) && this != null) await ShowBoard();
}
}
Then build the scene:
- Create a scene named
GameOverand add a Canvas (GameObject › UI) with three Text - TextMeshPro objects (score, status and board), an Input Field - TextMeshPro for the name and a Button to play again. - Add the
GameOvercomponent to the Canvas and drag each object into its field. - Add both
GameOverand your game scene (namedGamehere) to File › Build Profiles (Build Settings before Unity 6). - When a run ends, from your game code:
GameOver.Score = score; SceneManager.LoadScene("GameOver");
The scene draws straight away, then fills in the rank and the table once they arrive. On the first run it also shows the name field. Rich text is turned off on the board, so whatever a player types can't inject TextMeshPro tags.
5. Try it
Press Play, finish a run and you should see yourself at #1. To play as a second player, clear the saved player with Edit › Clear All PlayerPrefs. If the status says the leaderboard is unavailable, check the Console: a 404 means the metric or leaderboard key doesn't match, and in a WebGL build a 403 means the page's origin isn't in Allowed origins.
Next steps
- Add a daily or monthly board: create another leaderboard on
highscorewith a repeating schedule and read it withGetLeaderboard("daily"). Every score counts on every board that uses the metric. - Time-based games (speedruns, puzzles): use the aggregation
minand rank lowest first. - Every error code is in the Quickstart and every endpoint in the API reference.