- Home /
Score and Highscore - Highscore not saving, loading, or displaying.
Hi, I'm a beginner and am struggling with saving, loading and displaying a high score. The points work for the killed spawned objects and it resets to 0 when the player is killed and the game restarts. I want to save the score and for the system to check if it is higher than the previous saved high score then save the new high score. I've read the playerpref's information but I'm stuck. Thanks for any help. using UnityEngine; using UnityEngine.UI; using System.Collections;
public class GameController : MonoBehaviour
{
public GameObject[] hazards;
public Vector3 spawnValues;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;
public Text scoreText; //attach in Inspector
private int score;
public Text highscoreText; //attach in Inspector
static int highscore;
Text text;
void Awake()
{
text = GetComponent<Text>();
score = 0;
highscore = PlayerPrefs.GetInt("highscore");
}
void Start ()
{
score = 0;
UpdateScore ();
StartCoroutine (SpawnWaves ());
}
IEnumerator SpawnWaves ()
{
yield return new WaitForSeconds (startWait);
while (true) {
for (int i = 0; i < hazardCount; i++) {
GameObject hazard = hazards [Random.Range (0, hazards.Length)];
Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds (spawnWait);
}
yield return new WaitForSeconds (waveWait);
}
}
public void AddScore (int newScoreValue)
{
score += newScoreValue;
UpdateScore ();
}
void UpdateScore ()
{
scoreText.text = "Score: " + score;
}
void Update()
{
if (score > highscore)
{
highscore = score;
PlayerPrefs.SetInt("highscore", highscore);
highscoreText.text = "Highscore: " + highscore;
}
text.text = "Score: " + score;
}
void OnDestroy()
{
PlayerPrefs.SetInt ("highscore", highscore);
PlayerPrefs.Save();
}
}
I created the UI text objects and dragged them into the Inspector for the script. The score text numbers are visible and updating as the enemies are killed, so that works perfectly, just need to save and display the high score. Thanks.
Your answer
Follow this Question
Related Questions
Storing high score 2 Answers
Score and HighScore saving script [please help] 2 Answers
Adding High Score to Game menu from existing code? 1 Answer
Score counter breaking after adding points 2 Answers
PlayerPrefs Highscore problem 1 Answer