- Home /
Saving highscore with PlayerPrefs
So basically I want to save the highscore of the player, so when it closes the game and launch it again the same number (the current highscore) will be displayed. I know that you can do it using PlayerPrefs, but I'm getting some trouble with it. My normal code, without the PlayerPrefs method, is this one (it works fine):
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI;
public class Highscore Script : MonoBehaviour {
public static int highscoreValue;
Text highscore;
void Start () {
highscore = GetComponent<Text> ();
}
void Update () {
highscore.text = "Highscore: " + highscoreValue;
}
}
And then I tried to implement the PlayerPrefs, which ended in something like this:
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI;
public class HighscoreScript : MonoBehaviour {
public static int highscoreValue;
Text highscore;
void Start () {
highscore = GetComponent<Text> ();
highscoreValue = PlayerPrefs.GetInt("Highscore");
}
void Update () {
highscore.text = "Highscore: " + highscoreValue;
PlayerPrefs.SetInt("Highscore", highscoreValue);
PlayerPrefs.Save();
}
}
The problem is that, with this new code, the highscore is always 0. And with that I also can't really know if it is saving the highscore or not.
I'm not entirely sure so I won't post it as answer, but it might happen because you are doing this in Update. It would overwrite your highscore all the time.
You could try creating a seperate method that saves the highscore, which you only call when there is a highscore.
Something like:
public void SaveHighscore() {
PlayerPrefs.SetInt("Highscore", highscoreValue);
PlayerPrefs.Save();
}
Not sure when you decide whether the player got a highscore, but I made it public so you can access it in other scripts.
Answer by Trevdevs · Oct 16, 2018 at 03:18 AM
Following up with what the person said in the comment definently don't do this in the update function that is horribly inefficent although should work.
If you want to save the score when the player quits the game use this https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationQuit.html
Your answer
Follow this Question
Related Questions
How can i get the following script back on track to being a single level high score saver 0 Answers
Highscore won't save 3 Answers
PlayerPrefs save after quit? 2 Answers
How to save a high score 2 Answers