- Home /
Highscore with points and time
I'm making a highscore system for my game with the list method and I need to compare points and times to set the rank position.
I've already done this:
A script creates a "playerlist".
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class players
{
public List<PlayerData> pdata;
}
A script to set strings and ints
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class PlayerData
{
public int rank;
public string name;
public string time;
public int score;
}
To set the rank I need to compare score and time between players, if at some point there will be tie by score, the time will set the rank of the player ..
for example,
Player 1 - (Name: Bob - Score: 100 - Time 0:30) Player 2 - (Name: Bill - Score: 100 - Time 0:28)
Player 2 made 100 points in less time, so he will be ahead in rank.
How do I make this comparison to set the rank of each player?
Thanks
Answer by FM-Productions · May 05, 2017 at 12:20 PM
You can simply sort your List after a certain criterium, for example the score. And then the rank of the player would simply be the list index + 1. You could also implement your own sorting function as argument in .Sort() if you don't want do consider only the score.
pdata.Sort((x, y) => x.score > y.score); //either something like this, here you could implement your custom sorting logic
pdata = pdata.OrderByDescending(x => x.score); //or sort like this after an attribute
//assigning the ranks - should not be necessary anymore, since the list is already sorted like you want it
for (int i = 0; i < pdata.Count; i++){
pdata[i].rank = i+1;
}
Also, this post should be exactly what you are looking for (in case my code would not work) : http://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object