Saving score when app closes with PlayerPrefs

I want my highscore to save when my app closes. I have searched many ways but I’m struggling to write it in my code. I added the PlayerPrefs where I thought they should go, but when I test the app, my high score does not save :-(. Can anyone can help me out with where I’m going wrong!!!

#pragma strict

var scoreCount: GUIText;
var scoreValue: int;
var hasLost:boolean = false;
var bestScore: int = 0;
var lastBest: int = 0;
var buttonStyle: GUIStyle;
var isPaused: boolean;





function Start () {
        if(PlayerPrefs.HasKey("highScore")){
            bestScore = 0;
            } else{
        bestScore = PlayerPrefs.GetInt("highScore");
}
}

function Update () {
    if(Input.GetMouseButton(0)){
      rigidbody.AddForce (Vector3.forward * 15);
    }
    }
    {
    if(Input.GetMouseButtonUp(0)){
    Debug.Log ("I lifted the button");
    rigidbody.drag = 1;
    }
    }
    {
    if(Input.GetKeyDown (KeyCode.Escape));{
    OnBackPressed();
    }
    }

    var str:String;
   
    if(!hasLost) {
        str = "Score: " + scoreValue.ToString();
    } else {
        str = "Score:" + scoreValue.ToString() + "\nHigh Score:" + bestScore;
        if(bestScore > lastBest) str += "\nNEW RECORD!";
    }
    scoreCount.text = str;
   
    if(transform.position.y <-9) {
        if(!hasLost) {
            hasLost = true;
            lastBest = bestScore;
            if(scoreValue > bestScore) {
                bestScore = scoreValue;
            }
        }
    }
}

function OnGUI(){
    if(hasLost){
var buttonW:int = 300; // button width
    var buttonH:int = 100; // button height
   
    var halfScreenW:float = Screen.width/2.1; // half of the Screen width
    var halfButtonW:float = buttonW/2; // Half of the button width

        if(GUI.Button(Rect(halfScreenW-halfButtonW,Screen.height*.8,buttonW,buttonH),"Play Again", buttonStyle)){
            scoreValue = 0;
            hasLost = false;
            transform.position = Vector3(0.13,-0.968,-21.042);
            rigidbody.velocity = Vector3(0,0,0);
        }
    }
}

function OnTriggerEnter (col : Collider){
    if (col.gameObject.FindWithTag ("score"));
    {
    Debug.Log ("Score!!!");
    scoreValue += 1;
    //scoreCount.text = "Score: " + scoreValue;
    }
}

function OnBackPressed(){
    if(Input.GetKeyDown (KeyCode.Escape)){
    {       
    if(bestScore < scoreValue){
    PlayerPrefs.SetInt("highScore", bestScore);
    }
    }
    Application.Quit();
    }
}

The code is showing my high score when I need it to during the game, I just need the highscore to save when the app is closed.

Don’t you want to read the high score if the PlayerPrefs have the highscore key? Your line 17 sets the high score to zero if the player pref is present.

1 Like