简体   繁体   中英

Simple Scoreboard in Unity3D for Ranking and Placement for 1st, 2nd, and 3rd

I'm working on a simple scoreboard in unity that adds and subtract scores with buttons, but can't figure out how to have the scores rank from 1st, 2nd and 3rd place.

Just like in most of the games, I wanted to only showcase the first three highest score. Even though this example only showed two scores, there probably be up to 10 scores that this program needs to rank.

Any suggestions?

public class Scores : MonoBehaviour
{
    public Text scoreText;
    public Text scoreText2;
    public Text firstPlace;
    public Text secondPlace;
    public Text thirdPlace;
    public int score;
    public int score2;

    public void Addition()
    {
        score++;
        scoreText.text = "" + score;
    }

    public void Subtraction()
    {      
        score--;
        scoreText.text = "" + score;
    }

    private void Update()
    {
        if (score > score2)
        {
            firstPlace.text = "Texas A&M";
            secondPlace.text = "University of Houston";
            thirdPlace.text = "LSU"
        }
     }
}  

A Better way to achieve this is dictionaries:

// Create a dictionary
public Dictionary <float,string> scores = new Dictionary<float ,string>();

// Add scores you want to add
scores.Add(1,"SomeText");
scores.Add(4,"SomeOtherText");
scores.Add(3,"SomeOtherText");

// convert the keys into a list
float[] order = scores.Keys.ToList();
// sort array in reverse order
order.Sort.Reverse();

/// print the order
Console.Log("First Place"+scores[order[0]]);
Console.Log("Second Place"+scores[order[1]]);
Console.Log("Third Place"+scores[order[2]]);


References:
https://www.dotnetperls.com/sort-dictionary
https://www.geeksforgeeks.org/different-ways-to-sort-an-array-in-descending-order-in-c-sharp/

Please forgive me for any spelling mistakes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM