How do I use PlayerPrefs to save My Score?

As the question states, I want to display and save the player’s best score on the Game Over Scene. And every time the player beats their score, it replaces the previous one.

Here is my Score Script:

#pragma strict
static var currentScore : int = 0;

var offsetY : float = 40;
var sizeX : float = 100;
var sizeY : float = 40;
function Awake()
{
      currentScore = 0;
}
function OnGUI () {
	GUI.color = Color.yellow;
	GUI.Box (new Rect (Screen.width/2-sizeX/2, offsetY, sizeX, sizeY), "" + currentScore);
}

This is in my player script:

       GameMaster.currentScore += 1;

2 Answers

2

PlayerPrefs work by getting and setting values to a file.

To set an int value, use the following function. Name of file being whatever you’d like to call it. This will also overwrite any existing playerpref with the same name

PlayerPrefs.SetInt("NameOfFile", currentScore);

To read a playerpref, say at game startup, use the following function

currentScore = PlayerPrefs.GetInt("NameOfFile");

Will it matter if I place it within this: function GameOver(){ Application.LoadLevel("Game Over"); }

–

No, you can definitely do that. Just make sure Application.LoadLevel("Game Over"); is the last thing in the function, otherwise I'm pretty sure it won't get called :)

–

I'm not sure if this is correct, but: function GameOver(){ //save highscore if(score > PlayerPrefs.SetInt("GameMaster", currentScore); { currentScore = PlayerPrefs.GetInt("GameMaster"); } Application.LoadLevel("Game Over"); } I am getting a error in which it states: Assets/GameOver.js(9,58): BCE0044: expecting ), found ';'.

–

For some reason I'm still receiving the same error message. Maybe I need to make a reference to my score script. Thank You for your help. :)

–

Yes, if score or currentScore isn't in the script with this function, you will need a reference :)

–

You should check the Key first, if it exist then it will get score value from PlayerPrefs, otherwise will SetInt the PlayerPrefs. Do as following.

         if (PlayerPrefs.HasKey("highScore") )
		{
			if (GameScore.newScore > PlayerPrefs.GetInt("highScore") ) 
			{
				highScore = GameScore.newScore;
				PlayerPrefs.SetInt("highScore", highScore);
				PlayerPrefs.Save();
			}
		}
		else
		{
			if (GameScore.newScore > highScore ) 
			{
				highScore = GameScore.newScore;
				PlayerPrefs.SetInt("highScore", highScore);
				PlayerPrefs.Save();
			}	
		}

		Application.LoadLevel("GameOver");