Code setting 0 as the highscore [Read description]
The point of my game is that the timer ticks from 10 seconds, and you should tap the screen or space as close to 0 as possible. My code is checking if my current score is closer to cero than the highscore. This works perfectly exept the fact that the highscore is always 0. I can manually se the score to be 10, and it works. How can i not make this code set my highscore to be 0, but let the highscore start at 10?
public float counter = 10;
public float HighScore = 10;
public TextMesh text;
public TextMesh text3;
// Use this for initialization
void Start () {
HighScore = PlayerPrefs.GetFloat ("High", 0);
Time.timeScale = 1f;
}
// Update is called once per frame
void Update () {
counter -= Time.deltaTime;
text.text = "" + counter;
text3.text = "" + HighScore;
if (Input.touchCount > 0 || Input.GetKey (KeyCode.Space)) {
CheckHighScore ();
Time.timeScale = 0f;
}
if (Input.GetKey (KeyCode.A)) {
Application.LoadLevel ("level");
}
}
public void CheckHighScore(){
if(Mathf.Abs(counter) < Mathf.Abs(HighScore)) {
HighScore = counter;
PlayerPrefs.SetFloat ("High", counter);
}
}
}
Answer by rutter · Oct 22, 2015 at 02:15 PM
This line:
HighScore = PlayerPrefs.GetFloat ("High", 0);
The second argument is a default that will be used if High
is not yet set. If your default value is zero, you will end up getting a zero the first time you play, and that will be a tough score to beat!
The simplest solution is to use a better default:
HighScore = PlayerPrefs.GetFloat("High", 10);
Woah, that was pretty obvious and easy! Thank youy so much.