- Home /
Unity ignoring if statement for high score
Hi. So I want to implement a high score system in my game but for some reason unity ignored the if statement and makes the score you just got the high score, even if that score is lower than the score you got before. For example if i got 10, and that was my high score. Then if I them got 6, that would become the new high score, even if it is lower than 10. How would I fix this? Thanks.
time += (Time.deltaTime * 1.4f);
int besttime = 0;
int finaltime = (int) time;
guiText.text = Mathf.Ceil(finaltime).ToString();
PlayerPrefs.SetInt ("highscore", 0);
int highscore = PlayerPrefs.GetInt ("highscore");
if (finaltime > highscore) {
besttime = finaltime;
}
else if (finaltime < highscore) {
besttime = besttime;
}
PlayerPrefs.SetInt ("highscore", besttime);
Answer by getyour411 · Jan 30, 2014 at 08:39 AM
Please format your code. Why are you doing this:
PlayerPrefs.SetInt ("highscore", 0);
That's writing 0 to highscore so whatever was there is gone.
Answer by valim · Jan 30, 2014 at 01:37 PM
What's the point of this piece of code?
else if (finaltime < highscore) {
besttime = besttime;
}
No offense but you have no logic :)
PlayerPrefs.SetInt ("highscore", 0);
That's writing 0 to highscore so whatever was there is gone.
That was your problem. You've reseting the highscore every time.
I don't have any clue what's happening in that code. It is in update function?
My instinct says that the code shoud be something like this:
time += (Time.deltaTime * 1.4f);
int finaltime = (int) time;
guiText.text = Mathf.Ceil(finaltime).ToString();
int highscore = PlayerPrefs.GetInt ("highscore");
if (finaltime > highscore) {
PlayerPrefs.SetInt ("highscore", finaltime);
}