Reputation: 25
I have this attached to my hero object that gets destroyed . Could that be part of the problem? All I want to do is save the highscore then display it on my start scene. Here is the code:
public int highscore;
public int score;
void AddPoint1()
{
if (score > highscore) {
highscore = score;
PlayerPrefs.SetInt ("highscore", score);
PlayerPrefs.Save ();
}
}
Here is second script attached to empty object in start scene (different scene)
void OnGUI()
{
GUI.Label (new Rect (Screen.width / 2, Screen.height/2, 100, 100), "Highscore: " + PlayerPrefs.GetInt("highscore"), customGuistyle);
}
Upvotes: 1
Views: 4128
Reputation: 1
I think you should get the int to the string on your PlayerPrefs.GetInt Here is my code :
public Text Score;
public Text HighScore;
public bool increasing;
static int score;
static int highScore;
public Movement player;
void Start ()
{
score = 0;
highScore = PlayerPrefs.GetInt ("HighScore");
}
void Update ()
{
Score.text = " " + score + "m";
HighScore.text = " " + highScore + "m";
if (player.ground == true && increasing == true)
{
score = score + 1;
}
if (score > PlayerPrefs.GetInt("HighScore"))
{
highScore = score;
PlayerPrefs.SetInt ("HighScore", highScore);
PlayerPrefs.Save();
}
}
Upvotes: 0
Reputation: 21
I almost had the same problem, but i found the solution. I know this question is too old, but maybe i can help someone.
I had to save my PlayerPrefs before game closed. There the simple solution, just call method OnApplicationPause() and put inside your PlayerPrefs.
Upvotes: 0
Reputation: 413
From my knowledge of Unity you do not need to call PlayerPrefs.Save(), also I've noticed that you have the highscore stored locally and it is never defined, therefore you are comparing the score to a null value. Your new code would look like this:
public int score;
void AddPoint1()
{
if(score > PlayerPrefs.GetInt("highscore"))
{
PlayerPrefs.SetInt("highscore", score);
}
}
Also even if you initially set highscore to something, say 1. The code would work but as soon as you close the application and rerun it the highscore would be reset back to one, and then even if the player scored 2, it would override the PlayerPrefs highscore no matter what it is.
Upvotes: 1