Unity How to save high score for each specific level?

I have been using unity on and off for a year and still learning. I am trying to create a basic game where a player has to go through levels and collecting points under a time countdown on android. The player will have completed the level once it has hit an endtrigger which would display the amount of points collected along with the time taken to complete it. The high score will then be displayed from the multiplication of the points and time taken, which is simple.

The high score would have already been saved using playerprefs and the high score will then be displayed on the level select screen below each level (ex. lvl 1: 136, lvl2: 245, etc…). I have just learned how to save a simple int using playerprefs.

My problem is, how do I save the high score of each individual level and then display it in the level select screen using playerprefs.

Answer

As in my first comment – PlayerPrefs works with key-value pairs so you can do it like this.

// Setting values
PlayerPrefs.SetInt("Level1", 100);
PlayerPrefs.SetInt("Level2", 200);

// Getting values
int someint = PlayerPrefs.GetInt("Level1");
int someint2 = PlayerPrefs.GetInt("Level2");

So when you want to save it for each level you do something like this.

 //Save Score with scene name as the key and the score as the value
 PlayerPrefs.SetInt(SceneManager.GetActiveScene().name, _score);

You can put it anywhere you want. It will always get the name of the currently active scene as the key.

You can also save floats and strings and also delete entries.

For more information take a look at the Unity docs: https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

Leave a Reply

Your email address will not be published. Required fields are marked *