- Home /
I'm stuck with PlayerPrefs, for some reason it wont work, please help
public class HighScore : MonoBehaviour {
public int score;
public int highScore;
public Text scoreText;
public Text highScoreText;
// Use this for initialization
void Start () {
score = 0;
highScore = PlayerPrefs.GetInt("HighScore", highScore);
highScoreText.text = "High score: " + highScore;
setHighScore(score);
}
void OnTriggerEnter2D(Collider2D col){
if (col.name == "pacdot") {
score++;
scoreText.text = "Score: " + score;
setHighScore(score);
}
}
void setHighScore(int score){
if (score > highScore) {
highScore = score;
highScoreText.text = "High score: " + highScore;
PlayerPrefs.SetInt("HighScore", highScore);
PlayerPrefs.Save();
}
if(highScore > score)
{
highScore = score;
highScoreText.text = "High score: " + highScore;
PlayerPrefs.SetInt("HighScore", highScore);
PlayerPrefs.Save();
}
}
}
Answer by Adrian · Aug 26, 2015 at 01:03 PM
What are you trying to do with the second if
in the setHighScore()
function? You should only update the hight score when the current score has exceeded the high score. The if(highScore > score)
sets the high score to the lower current score, effectively always making score
and highScore
the same value.
I tried to set my high score, and yes i've done nonsense part with whole if(highScore > score). I removed that and set highscore to 0 in Start(), and now it works! Thanks for your help!
Answer by Mikea15 · Aug 26, 2015 at 01:11 PM
Check
highScore = PlayerPrefs.GetInt("HighScore", highScore);
The highScore inside the method call is the default value.. You can remove that, the default value is at 0.
Also, you can simplify a lot your setHighscore method.
void setHighScore(int score){
if (score > highScore) {
highScore = score;
}
highScoreText.text = "High score: " + highScore;
PlayerPrefs.SetInt("HighScore", highScore);
PlayerPrefs.Save();
}
Here's the reference for you, always search for your problems ;) http://docs.unity3d.com/ScriptReference/PlayerPrefs.GetInt.html
Also, maybe explain better your problem. WHAT doesnt work exactly. Cheers.
Hello! I set my highScore to 0, and removed if(highScore> score) part. Now it works, thanks for your help!