here is the script for this purpose, it includes how to sort player score and make UI of it:
using UnityEngine; using System.Collections.Generic; using UnityEngine.UI; using System.Linq;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
using System.Linq;
public class PlayerScore
{
public string name;
public int score;
}
public class UILeaderboard : MonoBehaviour
{
// This is object all your "Player" UI elements will be parented into
public Transform holder;
// Contains all players and their score
List<PlayerScore> players = new List<PlayerScore>();
// Contains all created "Player" UI elements
List<GameObject> textElements = new List<GameObject>();
// Just the original "Player" UI object we will be creating copy of
GameObject textPlayerElement;
void Start()
{
// Just cache the original UI text object you created
textPlayerElement.SetActive(false);
textElements.Add(textPlayerElement);
// Just add random players for testing
AddPlayer("Mike", 200);
AddPlayer("Ike", 50);
AddPlayer("John", 300);
}
public void AddPlayer(string name, int score)
{
var player = new PlayerScore();
player.name = name;
player.score = score;
// This will sort entire list by player score
players = players.OrderByDescending(x => x.score).ToList();
// Now create UI for this player
if(textElements.Count < players.Count)
AddPlayerUI(player);
// Now update the texts UI with the sorted score
UpdateTexts();
}
void AddPlayerUI(PlayerScore player)
{
// Create copy of UI inside holder
GameObject element = GameObject.Instantiate(textPlayerElement);
element.transform.SetParent(holder);
// Set the texts
textElements.Add(element);
}
void UpdateTexts()
{
for (int i = 0; i < players.Count; i++)
{
textElements[i].GetComponent<Text>().text = players[i].name;
textElements[i].transform.GetChild(0).GetComponent<Text>().text = players[i].score.ToString();
}
}
}
when you run this, and you did everything right, and I did everything right :D you should see few players with their names in UI.