Unity 2D Prototype part 6 – High Scores

      Comments Off on Unity 2D Prototype part 6 – High Scores

Next up we want to track the high scores the players get on the game. Create a new script, ScoreManager, and add it to the System game object.

In this script we have a few things of interest. First off we have a property called Scores that is a List<int>, which we’re going to use for tracking our 5 top scores. UpdateScores takes our new score which we’ll provide when the game ends, and makes sure it’s higher than the lowest high score. After that we add it to the scores list, do some sorting and keep the top 5 scores as our current scores, then save the scores. Saving and loading our high scores is pretty straight forward. Because we want the scores to persist for more than the current open session we need to save them to file. Unity provides us with a variable for the directory that data saved by our application should go and this variable will work regardless of the platform we’re targeting. For both Loading and saving the file we open a new FileStream object, giving it the path, in our case the default path + the file name “scores.txt”. The difference in loading and saving is only the access rights we’re opening the file with. Inside each method we have a Binary Formatter, which is a class that converts from whatever object type we’re using to a binary format that’s optimized for saving. For loading we deserialize the object from the file, for saving we Serialize the object in memory to the file.

In the Start method of the component we try to load the scores, but if no file is found and we don’t have a scores list loaded we initialize it with all 0 values and save the file.

In our SceneManager class we’ll update the NavigateToGameOver method to call into the score manager and update the score before we reset.

Now all that’s left is to update our HighScore screen to show all of our scores.

Create 5 text boxes and position them like so

We’ll add a new script to the high score canvas that will get the information we want to display to the screen and put it in our textboxes

As with our other scripts we need to add public variables for each textbox and wire them up in the editor

The OnEnable method will fire when the canvas becomes active when the user navigates to the screen.

Now when you run you’ll see your high scores on the screen. If they’re all 0 then you should play a round or two to fill in some scores.