A quick and simple example(high score board)

The topic came up in Skype today, and I didn’t really finish the high scoreboard in a game I was working on recently, so I’ve finnished up and pulled together a few little code segments into a fairly vanilla script for Unity.

So first off, if you didn’t know already, Unity lets you store and access ints, floats, and strings on the hard drive using PlayerPrefs. More than enough for a quick highscoreboard. Better yet, since the PlayerPref keys are different for each game you can keep the hard coded names when you reuse the script. (It also means you can’t access those PlayerPrefs anymore if you change the name of your game.)

string[] scoreData;
 
void Start () {
 
 //Get old scores from PlayerPrefs
 //We'll assume it's a top-5 board for this example
 scoreData = new string[5];
 
 for(int i = scoreData.Length; i > 0; --i)
 {
 //ie get string named "Highscore5", if blank set to/return "500,WUP"
 scoreData[i-1] = PlayerPrefs.GetString("Highscore"+i, (i*100).ToString() + ',' + "WUP");
 }
}

So now we should have a bunch of strings that should at least have a useable default value if not actual highscore data. Most importantly we’ve just defined the scores need to be stored; number first, followed by the name and separated by the Record Separator character.

Let’s assume the highscore table is all jumbled up (damn gremlins!) and we want to sort the scores so that the names/names are in correct order. It’s a short list so we’ll use bubble sort. Here’s a serious explanation and a cool video.

In order to sort the scores we need their values, it’s as simple as splitting the string and parsing the integer. I’ve thrown it into a static method below.

public static int ParseScore(string str) {
 
 //return int parsed out of string index 0 returned by splitting the string at commas
 return int.Parse(str.Split(new char[]{','})[0]);
}

Now we can dance the bubble sort dance:

//Sort this array, simple bubble sort with premature exit
void SortScores() {
 
 bool swapped;
 for(int i = scoreData.Length - 1; i > 0; --i)
 {
 swapped = false;
 for(int j = 0; j < i; ++j)
 {
 if(ParseScore(scoreData[j]) > ParseScore(scoreData[j+1]))
 {
 Swap<string>(ref scoreData[j], ref scoreData[j+1]);
 swapped = true;
 }
 }
 if(!swapped)
 {
 break;
 }
 }
}

This sorts out the scores into ascending order (lows-left). So we have some scores being read and sorted. This example took a little longer than I expected (doesn’t everything?) so I’ll wrap up with the GUI code and the Add-Score code later.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s