- Home /
Saving a value if it is larger than the current value...
I have a score script right here:
 using UnityEngine;
 using System.Collections;
 
 public class ScoreSystem : MonoBehaviour {
     
     public GUIText guiText;
     public int scoreValue;
     
     public static bool hasPlayed = false;
     
     // Use this for initialization
     void Start () {
 
     }
     
     // Update is called once per frame
     void Update () {
         if(Move.playerAlive) {
             scoreValue++;
         }
         
         guiText.text = "" + scoreValue;
         
         PlayerPrefs.SetInt("scoreValue", scoreValue);
         
         if(!Move.playerAlive) {
             PlayerPrefs.Save();
             hasPlayed = true;
         }
     }
 }
What I want is to have another PlayerPrefs value, that will only record the highest score (high score). Can anyone help me out?
Thanks in advance!
Answer by SubatomicHero · Jul 25, 2013 at 10:51 AM
You will need an if statement that checks the current score against the stored highscore:
 // at the top
 public int highScore;
 
 // in your start functiion
 void Start(){
     highScore = PlayerPrefs.GetInt("highScore");
     if (highScore == 0){
         highScore = 0;
     }
 }
 
 // in your update function
 void Update(){
     // ...
     if (scoreValue > highScore){
         PlayerPrefs.SetInt("highScore", scoreValue);
     } else {
         PlayerPrefs.SetInt("highScore", highScore);
     }
 }
I think this as a basic recipe may help you get started.
A-W-E-S-O-$$anonymous$$-E! Works like a charm! This was amazingly simple, yet organized, and that is what makes good code. Thanks dude!
Answer by Seth-Bergman · Jul 25, 2013 at 10:48 AM
pretty simple, just say:
 if(PlayerPrefs.GetInt("High Score") < scoreValue)
 PlayerPrefs.SetInt("High Score", scoreValue);
Answer by sona.viswam · Jul 25, 2013 at 11:52 AM
 // Declare variables     
 private int highScore;
 public int scoreValue;
 // Use this for initialization 
 void Start(){
     if (HasKey("highScore"))
     {
         highScore = PlayerPrefs.GetInt("highScore");
     }else
     {
         PlayerPrefs.SetInt("highScore", 0);
         highScore = 0;
     }      
  }
 // Update is called once per frame
 void Update(){
     if (scoreValue > highScore){
         PlayerPrefs.SetInt("highScore", scoreValue);
         highScore = scoreValue ;
     } 
 }
Your answer
 
 
             Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Getting Error Object reference not set to an instance of an object 1 Answer
Trap Door Question 1 Answer
what's wrong with this script? 2 Answers
Need help syntax error 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                