- Home /
Setting, saving and getting info from PlayerPrefs, i can't save and call a highscore
I don't understand how to set my high score to save at the end of each game, i've looked at many things for high score with player prefs and have copied and pasted code but i don't think my script actually has a reference for wherever the data is supposed to be saved when i use PlayerPrefs. Do i need to make a game object to store or is it just supposed to know where to save? i'm really confused. here's everywhere i have reference to high score and PlayerPrefs in my script, what am i missing?
public GUIText scoreText;
public GUIText restartText;
public GUIText gameOverText;
public GUIText yourscoreText;
public GUIText highscoreText;
private bool gameOver;
private bool restart;
private int score;
static int highscore;
private void Start()
{
gameOver = false;
restart = false;
restartText.text = "";
gameOverText.text = "";
yourscoreText.text = "";
highscoreText.text = "";
score = 0;
highscore = PlayerPrefs.GetInt("highscore", highscore);
UpdateScore();
StartCoroutine(SpawnWaves());
}
//skipping some lines
public void AddScore(int newScoreValue)
{
score += newScoreValue;
UpdateScore();
}
void UpdateScore()
{
scoreText.text = "Score: " + score;
}
public void GameOver()
{
gameOverText.text = "Game Over!";
yourscoreText.text = "Your Score: " + score;
gameOver = true;
if (score > highscore)
{
highscoreText.text = "Highscore: " + score;
PlayerPrefs.SetInt("highscore", highscore);
}
PlayerPrefs.Save();
}
Answer by OneCept-Games · Jan 02, 2018 at 02:52 PM
Are you calling GameOver() when your game is over?
yes i am, it's triggered when the player is destroyed by an object
You are updating a variable called "score" but you are saving another one called "highscore". "highscore" in your code is never updated with a new value, so you will always save and retrieve 0.
thank you! i cant believe i missed that, it makes perfect sense. appreciate the help