Im trying to make a scoreboard for my game where it automatically displays the name/score ascending from smallest number to biggest number (C#)

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();
        }
    }
}
  • now create new gameObject, add Text component to it and name object Text_Name. Create new object with Text and name it Text_Score, make it child of Text_Name.
  • create new object and name it Holder, make your Text_Name child of this holder. You will have Vertical Layout Group component on Holder object.
  • attach the provided script onto holder. Now drag & drop Holder object into holder field of added script.

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.

/r/Unity3D Thread