Leaderboard Algorithm for Unity 3D

Everistus Akpabio
November 18, 2018

A simple leader-board algorithm to keep your game engaging.

While working on a project, Fingerprint Scanner , I thought a cool feature to add to it would be a leaderboard system. The project was made in unity 3D using c#, at the time I had no real knowledge of SQl and databases and we did not plan on creating or using a database just for storing about 7 players’ name and score.

Note:When posting code I will only be posting useful snippets from important functions. Look out for a post update with a reference zip file, this can be found at the end of the tutorial.

The approach to solving this can be broken into 5-steps:

  1. Getting data - [user input name] + game generated score
  2. Algorithm for sorting data
  3. Saving data
  4. Retrieving data
  5. Displaying data
Getting Data

This was easy, at the end of the game, I just checked the available leaderboard rows to see if currentScore > anyScoreOnTheLeaderboard, getUserInput, else: show gameOverScreen()

Algorithm for Sorting Data

I created a leaderboard class with playerName (string) and playerScore (int) fields, a leaderboardManager with an array[ ] of leaderboards. The sorting algorithm is quite simple, it’s just like a high score algorithm (if currentScore < highScore { highScore = currentScore}) with sorting.

  1. Sorting through the leaderboard array in a for loop
  2. If currentScore > leaderboardItem[i]
  3. Replace the currentScore as the leaderboardItem[i].playerScore
  4. Replace the playerName as the leaderboardItem[i].playerName
  5. Sort the array, this is in ascending order
  6. Reverse the array in descending order by score so the highest stays on top.
  7. Call the coroutine to save the leaderboard to the server.

C# has an Array Sort and Array Reverse function that helped with this, otherwise one would have to write and algorithm for that.

Saving data

For saving and getting data from the server, I leveraged unitys WWWForm to send and receive http requests from the server. This send a post request to the server and the server side of things will be handled with php. So turning the objects in our array to strings will look like this

string leaderboard = "";
for (int i = 0; i < leaderboardList.Length; i++)
{
    if (leaderboardList[i].playerName != null && leaderboardList[i].playerName != "")
    {
        leaderboard += leaderboardList[i].playerName.Trim() + ",";
        if (i == leaderboardList.Length - 1)
        {
            leaderboard += leaderboardList[i].playerScore.ToString();
        }
        else leaderboard += leaderboardList[i].playerScore.ToString() + ",";
    }
}

This will create a csv string like: “John Doe,84,Jane Doe 95” . post it as a form!

Retrieving and Displaying Data
Whenever you need to get back the leaderboard, make another http request to the server and pass the returned string to a parser to build the leaderboard object again, the parser looks like this:

private Leaderboard[] buildLeaderboard(string text)
{
    string[] a = text.Trim().Split(',');
    Leaderboard[] leaderboard = new Leaderboard[7];
    int j = 0;
    int k = 1;
    for (int i = 0; i < leaderboard.Length; i++)
    {
        try
        {
            leaderboard[i] = new Leaderboard(a[j], Convert.ToInt32(a[k]));
        }
        catch (Exception)
        {
            leaderboard[i] = new Leaderboard("", 0);
        }
            j += 2; k += 2;
        }
    return leaderboard;
}
                            

This builds your array from the csv values and you can sort and display it on your UI. Issues I experienced with this approach was; scalability (adding more field to the leaderboard required a lot of tweaking), some servers do not allow read and write permissions from .txt files ☹ and non-functional async calls.

In conclusion, this was a quick and dirty solution for a simple leaderboard, I wouldn’t approach it this way for a large-scale storage solution, rather than use csv values, JSON would be a better option and Firebase, by google, offers a realtime backend for all your cloud storage needs and more.