How to save a players high score for next scene?

Hello All,

The problem: Now that i have my scoring working i need to save the players high score. If they get a new high score then it will need to replace it with their new score.

Question: How do i set these getters and setter for it to save and pass the high score to the end scene?

Additional: I have already set an instance for my score which is where i run into problems as i started getting errors.

Code for scene 1:

public class Score : MonoBehaviour
{

public static Score instance { get; private set;}
public static int score = 0;

void Awake ()
{
    score = 0;
    InvokeRepeating("increaseScore", 1, 1);

}

public void Update ()
{
    score++;
    // Set the score text.
    guiText.text = "Score: " + score;
    instance = this;

}

}

Code for end scene:

public class endScore : MonoBehaviour {

// Use this for initialization
void Update () {

    // Set the score text.
    guiText.text = "Score: " + Score.score;

}

}

To summarise:

  1. I need the save the players score from the first block of code as highscore.
  2. Make some sort of comparison to only update if it is a highscore.
  3. echo it out in the second block of code in the next scene.

Thanks for any help in advance,

Max

P.s. Got to the stage where im just staring at the screen now and just cant get it to work!!

Check out the saving data tutorial

You have a few options. You could use PlayerPrefs which can save data to a .txt file which can be accessed, this isn’t secure so it shouldn’t be used with important info but rather with player preferences. eg: brightness, music on/off, controls etc… So you could use that or do something encrypted but for simplicity’s sake, let’s assume you’ll just use PlayerPrefs. Here is an example:

public class Score : MonoBehaviour
{

public static Score instance { get; private set;}
public static int score = 0;
public static int highscore;
public static int points;

void Awake ()
{
    score = 0;
    InvokeRepeating("increaseScore", 1, 1);

}


public void Update ()
{
    score++;
    // Set the score text.
    guiText.text = "Score: " + score;
    instance = this;
    

}
void OnDisable(){
    PlayerPrefs.SetInt ("highscore", highscore);
    PlayerPrefs.SetInt("Score",points);

    if(PlayerPrefs.GetInt("Score")>PlayerPrefs.GetInt("highscore")){
	highscore=points;
	PlayerPrefs.SetInt("highscore",highscore);

   }

 }

}

Code for end scene:

public class endScore : MonoBehaviour {

   public static void int score;
   public static void int highscore;

// Use this for initialization
void Update () {
    score=PlayerPrefs.GetInt("Score");
    highscore=PlayerPrefs.GetInt("Highscore");
    // Set the score text.
    guiText.text = "Score: " + score + " Highscore:" + highscore;

}


}

In the next scene you can just call PlayerPrefs.GetInt(“Score”) to get your score from the previous scene which gets saved in a .txt file. Hope this helps.