A UI component that fetches and displays a leaderboard in a TextRenderer. OnStart calls DisplayLeaderboard which gets a leaderboard service for a stat, configures aggregation/sort, refreshes entries, then builds a text list showing country, rank, name and 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.SetAggregationMin();
_scoreBoard.SetSortAscending();
_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}" );
}
}
}