How to create a simple Top10 for your Unity game with Firebase
May 22, 2015 • Marcelo Frantz
You are finishing up your single-player game, already wrote the end screen… but something feels wrong. Something is missing. Your player has no idea how well he played, he sees his score but has no idea how other people finished.
Don’t worry! Having a Top 10 screen is quick and easy using Firebase. It’s a service that provides you with a JSON database - so you get no real processing online, and no way to have a “server” so to speak - but it has a free tier and data validation rules that should be enough for a simple game.
Start by creating an app in Firebase. When you are done, go to https://yourApp.firebaseio.com to enter the Forge. This articles assumes your database will have the following structure:
The ID is auto-generated when data is posted to firebase and acts as a key - you could use a unique player ID for this. cat is a category, such as if the player died or finished the game, etc. time is an auto-generated value.
As security rules, use the following to make sure your data is validated to some extent and that no one can write on everything or otherwise mess with already existing content:
The score validation is also where you could do some sort of validation - something along the lines of && newData.val() <= yourMaximumScore.
And that’s it, you are done with the server side! For the client/game side, we will not use Firebase’s default client: it won’t work out of the box, specially if you are using the web player, so we’ll use UnityHTTP and the REST API. Just download the master revision and extract it somewhere in your project.
We’ll use two scenes. The first one shoud be your endgame scene - attach a script to an object, a button for example, with the following code that will upload the player’s score:
Now create your Top10 scene. Start with a canvas and create an easy to use structure such as this:
Project structure (Unity)
On the screenshot, success, death and failure are category images that will be activated based on the returned content.
Attach a script to your Canvas with the following content:
And… done! Now you have a Top10 screen such as the one on the header of this post, from the game SCRUM’ed!