A UI component that displays a leaderboard by fetching a leaderboard service for a published package stat and writing entries to a TextRenderer. It configures aggregation and sorting, refreshes the board asynchronously, then builds a text block showing country code, rank, display name and a mm:ss formatted time.
using Sandbox;
using System;
using System.Threading.Tasks;
public sealed class LeaderBoardDisplay2 : 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", "BestTimeLeaderboard" );
_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}: {TimeSpan.FromSeconds( entry.Value ):mm\\:ss}";
// Log.Info( $"#{entry.Rank} {entry.DisplayName}: {entry.Value}" );
}
}
}