Marco
Marco

Reputation: 43

Sorting a List <string, int> in Unity c#

I'm trying to make a rankingtable for some university work. The better way that came in mind was creating a List with String, Integer for each position. I searched in the documentation : https://unity3d.com/es/learn/tutorials/modules/intermediate/scripting/lists-and-dictionaries?gq=sort where i found the perfect example for my problem, so i started working. Now, i've created the Interfece:

public class Name_Puntuation: IComparable

public string namePlayer;
public int puntuation;

public Name_Puntuation( string newNomPlayer, int newPuntuation){

    nomPlayer = newNomPlayer;
    puntuation= newPuntuation;

}

public int CompareTo(Name_Puntuation other){

    if (other == null) {
        return 1;

    }

    return Puntuation - other.Puntuation;
}

I also added to my GameController what i want to do with the list. This class controlls the canvas of the game. We print all the information to textfields, and so i wanted to do with the ranking:

public class GameController : MonoBehaviour {

    public List <Name_Puntuation> ranking;

    void Start () {

        playerName= GetComponent<MenuController> ().inp; //name the player choosed

        ranking = new List<Name_Puntuation> ();

    }

    void Update () {  }

    public void Ranking(){
        int puntuation= punts;
        ranking.Add (new Name_Puntuation(playerName, puntuation)); 

        ranking.Sort ();

        foreach (Nom_Puntuacio p in ranking) {

            print (p.playerName+ " " + p.puntuation);

        }

    }
}

but now I'm stuck. I want to add the information to the list when the game is finnished. When do i have to call the function? rankig.sort(); will sort the puntuation (integer) of each player? AN dlast question, how do I have to restart the process to create a new player? Any advice will be very helpfull.

Thanks, Marco

Upvotes: 1

Views: 13422

Answers (1)

Wojciech Rak
Wojciech Rak

Reputation: 600

If I understand correctly, you want sort "puntuation (integer) of each player", so maybe the solution will be to use

ranking = ranking.OrderBy(x => x.puntuation).ToList();

or

ranking = ranking.OrderByDescending(x => x.puntuation).ToList();

Instead of:

ranking.Sort();

If I'm wrong please correct me

Upvotes: 5

Related Questions