[img]https: //i.sstatic.net/v8jLyPQo.png[/img]
Ниже приведен скриншот таблицы лидеров в Unity

Код: Выделить всё
public class LeaderboardManager : MonoBehaviour{
public GameObject rowPrefab;
public Transform rowParent;
private List leaderboardEntries = new List();
public List balls = new List(); // List of ball Rigidbody2D components
public List playerIDs = new List(); // List to store player IDs
public List playerNames = new List(); // List to store player names
//public TextMeshProUGUI leaderboardText; // UI Text component for leaderboard display
public Transform finishLine;
// Start is called before the first frame update
void Start()
{
UpdateLeaderboardUI();
//stopAnimation();
}
// Update is called once per frame
void Update()
{
UpdateBallPositions();
UpdateLeaderboardUI();
}
public void AddBallToList(Rigidbody ball, string playerID, string playerName)
{
balls.Add(ball);
playerIDs.Add(playerID); // Add player ID
playerNames.Add(playerName); // Add player name
}
void UpdateBallPositions()
{
// Combine the ball data (rigidbody, player ID, and player name) into a list and sort by distance to the finish line
var ballData = balls
.Select((ball, index) => new { Ball = ball, PlayerID = playerIDs[index], PlayerName = playerNames[index] })
.OrderBy(data => Vector3.Distance(data.Ball.position, finishLine.position)) // Sort by distance
.ToList();
balls = ballData.Select(data => data.Ball).ToList();
playerIDs = ballData.Select(data => data.PlayerID).ToList();
playerNames = ballData.Select(data => data.PlayerName).ToList();
}
// Update the leaderboard UI with the real-time positions of thels
void UpdateLeaderboardUI()
{
int maxPlayersToShow = Mathf.Min(10, balls.Count);
foreach (var entry in leaderboardEntries)
{
Destroy(entry);
}
leaderboardEntries.Clear();
Debug.Log("Rank Prefab: " + rowPrefab);
Debug.Log("Leaderboard Parent: " + rowParent);
for (int i = 0; i < maxPlayersToShow; i++)
{
// Instantiate a new leaderboard entry
GameObject newRank = Instantiate(rowPrefab, rowParent);
TextMeshProUGUI[] texts = newRank.GetComponentsInChildren();
texts[0].text = "#" + (i + 1); // Rank
texts[1].text = playerIDs[i]; // Player ID
texts[2].text = playerNames[i]; // Player Name
leaderboardEntries.Add(newRank); // Keep track of this entry
//Debug
float distance = Vector3.Distance(balls[i].position, finishLine.position);
Debug.Log((i + 1) + ". ID: " + playerIDs[i] + " - Name: " + playerNames[i] + " - Distance: " + distance.ToString("F2"));
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... ager-has-n