- Home /
Problems with saving/loading score with PlayerPrefs [C#]
Hey, I am having troubles getting playerprefs to save and load a value (in this case I want it to save the highest score). I have a scoresystem in my Player.cs script.
using UnityEngine;
using System.Collections;
public class Lose : MonoBehaviour
{
private int buttonWidth = Screen.width / 2;
private int buttonHeight = 50;
void Start()
{
PlayerPrefs.SetInt("Player Score", Player.Score);
getHighScore();
}
void OnGUI ()
{
GUI.Box (new Rect (Screen.width / 2 - buttonWidth / 2, 0, buttonWidth, buttonHeight), "You lost");
if (GUI.Button (new Rect (Screen.width / 2 - buttonWidth / 2, 75, buttonWidth, buttonHeight), "try again"))
{
Application.LoadLevel (1);
}
GUI.Label (new Rect (Screen.width / 2 - buttonWidth / 2, 195, buttonWidth, buttonHeight), "Score " + Player.Score);
GUI.Label (new Rect (Screen.width / 2 - buttonWidth / 2, 205, buttonWidth, buttonHeight), "High Score " + PlayerPrefs.GetInt("Player Score"));
}
void getHighScore()
{
if (Player.Score > PlayerPrefs.GetInt("Player Score"))
PlayerPrefs.SetInt("Player Score", Player.Score);
}
}
When I build and run the game both score field are the same. Does anyone know a fix for this?
Answer by dubbreak · Feb 16, 2013 at 12:06 AM
You are setting them to equal before you check so they are always going to be equal.
In Start() (which happens every time that script is enabled) you are setting the player prefs score to your current score. So when you check in getHighScore they are the same.
Try commenting out the initial set:
void Start()
{
//PlayerPrefs.SetInt("Player Score", Player.Score);
getHighScore();
}
That way if will only update the player prefs score if the player's current score is higher than the previously saved one.
Also from a style standpoint you should name getHighScore something like UpdateHighScore or UpdatePersistentHighScore. Functions that use the verb "get" generally return something. Set high score might be ok as well. Just a critique (which most people take poorly), so please disregard if that's the way you like it.