A UI component that fetches and displays a leaderboard in a TextRenderer. On start it requests a leaderboard by stat and name, configures aggregation/sort, refreshes it asynchronously, then writes each entry (country, rank, name, rounded value) into the TextRenderer.
using Sandbox;
using System;
using System.Threading.Tasks;
public sealed class LeaderBoardDisplay : Component
{
[Property] TextRenderer boardText;
protected override void OnStart()
{
// Call this whenever you want to display/update the leaderboard
DisplayLeaderboard();
}
public async Task DisplayLeaderboard()
{
// You fetch the stats from the package your organization published. You set your package name when publishing.
var _scoreBoard = Sandbox.Services.Leaderboards.GetFromStat( "punkwithapomp.chicken_escape", "HighScoreLeaderboard" );
_scoreBoard.SetAggregationMax();
_scoreBoard.SetSortDescending();
_scoreBoard.MaxEntries = 15;
boardText.Text = "LOADING...";
await _scoreBoard.Refresh();
boardText.Text = "";
// Loop over the entries and add them to the TextRenderer
foreach ( var entry in _scoreBoard.Entries )
{
boardText.Text += $"\n{entry.CountryCode} #{entry.Rank} {entry.DisplayName}: {Math.Round( entry.Value, 0 )}";
// Log.Info( $"#{entry.Rank} {entry.DisplayName}: {entry.Value}" );
}
}
}