I have the scoring working just fine but when the game restarts it doesn’t save the highscore and just resets everything back to 0. I am very new to coding in C# and would very much appreciate the help with getting this code correct so that it saves my highscore. The UI I am using is a text UI not a GUI. Thank you in advanced.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour {
public static int score;
public static int highscore;
Text text;
void Start()
{
text = GetComponent<Text> ();
score = 0;
highscore = PlayerPrefs.GetInt ("highscore", highscore);
}
void Update()
{
if (score > highscore);
highscore = score;
text.text = "" + score;
PlayerPrefs.SetInt ("highscore", highscore);
}
public static void AddPoints (int pointsToAdd)
{
score += pointsToAdd;
}
public static void Reset()
{
score = 0;
}
}
The code
void Update(){
if (score > highscore);
highscore = score;
text.text = "" + score;
PlayerPrefs.SetInt ("highscore", highscore);
}
is the same as
void Update(){
if (score > highscore){
}
highscore = score;
text.text = "" + score;
PlayerPrefs.SetInt ("highscore", highscore);
}
that is, you’re always setting highscore to the current score. Instead you probably want to use brackets as follows
void Update(){
if (score > highscore){
highscore = score;
text.text = "" + score;
PlayerPrefs.SetInt ("highscore", highscore);
}
}
https://unity3d.com/learn/tutorials/modules/beginner/scripting/if-statements
You also probably want to set the text.text to highscore in start
void Start()
{
text = GetComponent<Text> ();
score = 0;
highscore = PlayerPrefs.GetInt ("highscore", highscore);
text.text = highscore.ToString();
}
try using:
void OnDestroy()
{
PlayerPrefs.SetInt ("highscore", highscore);
PlayerPrefs.Save();
}
to actually save the PlayerPref.
(hope it helps anyone with similar issues)
Where are you displaying the high score?
This line:
text.text = "" + score;
Is only ever displaying the score, and when you reload the game that’s going to be 0 at the beginning. If you want it to display the high score then use that variable instead.
Also, to avoid confusion, you should get into the habit of indenting things properly. Instead of:
void Update()
{
if (score > highscore)
highscore = score;
text.text = "" + score; }
Line up the braces…
void Update()
{
if (score > highscore)
{
highscore = score;
}
text.text = "" + score;
}
And your Awake
function is indented too far. That combined with the brace at the end of the line in Update makes it look like you’re declaring Awake
inside of Update
. Just a friendly tip on style that will make looking at your code much easier.
What if the user delete the game and then download it after 1 month will still be saved the high score?