Search code examples
unity-game-enginesaveloadlocal-storagescoring

Unity3D PlayerPrefs issue


I am having an issue, when I lower the score from 10 to lets say 9 it changes the highscore anyway even though it is a lower number. Here is the code:

var score : int;
var highscore : int;

function Start(){
    highscore = PlayerPrefs.GetInt("highscore");
    score = 9;
    if(score > highscore){
        highscore = score;
        PlayerPrefs.Save();
    }
}

function OnGUI(){
    GUI.Label(Rect(10,10,100,20), score.ToString() );
    GUI.Label(Rect(10,50,100,20), highscore.ToString() );
}

Solution

  • You're using GetInt but you're not using SetInt afterwards, so your PlayerPrefs.Save() call isn't actually saving anything new.

    Try using SetInt before Save():

    if(score > highscore){
        highscore = score;
        PlayerPrefs.SetInt("highscore", highscore);
        PlayerPrefs.Save();
    }