Hello, So I have made a fully functional Leaderboard System that will display the top 3 scores. The only problem is, is that only the highest score will display.
Example:
Name Score
Name Score
Name Score
Instead of what it is supposed to look like:
Name1 Score1
Name2 Score2
Name3 Score3
This is my current code and I am using an IEnumerator to display the leaderboard.
What needs to happen is when there is a new highscore, highscore 3 becomes, highscore 2, highscore 2 becomes 1 and highscore1 becomes the new highscore. Thanks if you can help in advanced!
class HighscoreBoard
{
public class HighscoreRecord
{
public string Name;
public int Score;
}
public List<HighscoreRecord> Records = new List<HighscoreRecord>();
public void AddRecord(string name, int score)
{
Records.Add(new HighscoreRecord()
{
Name = name,
Score = score
});
Records = Records
//Sort
.OrderByDescending(p => p.Score)
//Take first 3
.Take(3)
.ToList();
string recordsAsString = String.Join(";",
Records
.Select(RecordToString)
.ToArray()
);
PlayerPrefs.SetString("Highscores", recordsAsString);
}
public void ReadHighscores()
{
if (!PlayerPrefs.HasKey("Highscores")) return;
Records = PlayerPrefs.GetString("Highscores")
.Split(';')
.Select(RecordFromString)
.ToList();
}
string RecordToString(HighscoreRecord record)
{
return record.Name + ':' + record.Score;
}
HighscoreRecord RecordFromString(string str)
{
string[] parts = str.Split(':');
return new HighscoreRecord()
{
Name = parts[0],
Score = Int32.Parse(parts[1])
};
}
}
Of course there is a pinch of Linq magic, but it’s small and handy.
You are essentially assigning highScore3 to all other scores.
EDIT: I think that you are under the assumption that the left gets assigned to the right, which is why the following looks correct. The left is always the updated value and the right is the value that it gets updated to.
You want to reverse the variables in respect to “=”. I brought all the assignments up to the top since it will still work and it is easier to understand the change IMO.