My game uses PlayerPrefs to save and load values for the last played Score and Highscore variables (both integers). So far everything’s functional except for one thing: when the scene is changed, i.e. back to the main menu or to the options menu, then back to the main game scene, the game doesn’t count up the score the next time it is run; in other words, the score variable doesn’t count up until the player dies at least once and refreshes. Well, now that I’ve explained all of that, here’s all my related code to the issue:
The Death() method of my Player Movement script:
void Death() {
IsAlive = false;
PlayerPrefs.SetInt("Score", Score.scoreValue);
if (Score.scoreValue > PlayerPrefs.GetInt("Highscore")) {
PlayerPrefs.SetInt("Highscore", Score.scoreValue);
}
Instantiate (DeathEffect, this.gameObject.transform.position, Quaternion.identity);
GameOver gameOver = GameObject.Find("Main Camera").GetComponent<GameOver>();
gameOver.DisplayGameOverGUI();
gameOver.gameOverPanel.gameObject.SetActive(true);
Score score = GameObject.Find("Main Camera").GetComponent<Score>();
score.scoreText.gameObject.SetActive(false);
}
Score.cs:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Score : MonoBehaviour {
public static int scoreValue;
public Text scoreText;
void Start() {
scoreValue = 0;
InvokeRepeating("CountScore", 1, 0.5f);
}
void Update() {
scoreText.text = "Score: " + scoreValue + "
Highscore: " + PlayerPrefs.GetInt(“Highscore”);
}
public void CountScore() {
if(Movement.IsAlive == true) {
scoreValue++;
}
}
}
GameOver.cs:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
public class GameOver : MonoBehaviour {
public Text gameOverText;
public GameObject gameOverPanel;
void Start() {
gameOverPanel.gameObject.SetActive(false);
}
public void DisplayGameOverGUI() {
if (!Movement.IsAlive) {
if(PlayerPrefs.GetInt("Highscore")>=(PlayerPrefs.GetInt("Score"))) {
gameOverText.text = "Score: " + Score.scoreValue + "
Highscore: " + PlayerPrefs.GetInt(“Highscore”) + "
You got " + (PlayerPrefs.GetInt(“Highscore”) - (PlayerPrefs.GetInt(“Score”))) + " lower than your highscore. Pretty close!";
}
if (PlayerPrefs.GetInt(“Score”) >= (PlayerPrefs.GetInt(“Highscore”))) {
gameOverText.text = “Score: " + Score.scoreValue + "
Highscore: " + PlayerPrefs.GetInt(“Highscore”) + "
You beat your highscore by " + (PlayerPrefs.GetInt(“Score”) - (PlayerPrefs.GetInt(“Highscore”))) + " points!”;
}
}
}
public void PlayAgain() {
SceneManager.LoadScene("Game");
Movement.IsAlive = true;
Score.scoreValue = 0;
}
public void QuitGame() {
SceneManager.LoadScene("Menu");
Score.scoreValue = 0;
}
}
The Start() method of MenuGUI:
void Start() {
scoreText.text = "Latest Score: " + PlayerPrefs.GetInt("Score") + "
Highscore: " + PlayerPrefs.GetInt(“Highscore”);
}
Hopefully that helps illustrate and explain my situation… Thanks in advance