Google Drive of Project
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameControl : MonoBehaviour
{
public static GameControl instance; //A reference to our game control script so we can access it statically.
public Text scoreText; //A reference to the UI text component that displays the player's score.
public Text highscoreText; //A reference to the UI text component that displays the player's highscore.
public GameObject gameOvertext; //A reference to the object that displays the text which appears when the player dies.
private int highScore = 0; //The games highscore
private int score = 0; //The player's score.
public bool gameOver = false; //Is the game over?
public float scrollSpeed = -1.5f;
void Start()
{
highScore = PlayerPrefs.GetInt("HighScore");
highscoreText.text = "HighScore: " + highScore.ToString();
}
void Awake()
{
//If we don't currently have a game control set this one to be it otherwise destroy this one
if (instance == null)
instance = this;
else if(instance != this)
Destroy (gameObject);
}
void Update()
{
//If the game is over and the player has pressed some input
if (gameOver && Input.GetMouseButtonDown(0))
{
//reload the current scene.
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
public void BirdScored()
{
//The bird can't score if the game is over.
if (gameOver)
return;
//If the game is not over, increase the score and set highscore
score++;
//adjust the score text.
scoreText.text = "Score: " + score.ToString();
// Check if this score beats the highscore
//if (score > highScore)
//{
// highScore = score;
// PlayerPrefs.SetInt("HighScore", highScore);
//}
//highscoreText.text = "HighScore: " + highScore.ToString();
}
public void BirdDied()
{
//Activate the game over text.
gameOvertext.SetActive(true);
//The game is over.
gameOver = true;
// Check if this score beats the highscore
if (score > highScore)
{
highScore = score;
PlayerPrefs.SetInt("HighScore", highScore);
}
highscoreText.text = "HighScore: " + highScore.ToString();
}
}
我希望显示高分,并在玩家死亡时更新。基本分数工作正常,但我无法更新高分。如果有人可以帮我解决这个问题,我将不胜感激。如果您需要查看其他代码,请让我知道您的想法并着手去做。
您需要将游戏状态逻辑与游戏外状态逻辑分开。
例如,我的一个项目有 a static1 class在不依赖 MonoBehaviour 组件的情况下保存我感兴趣的所有统计信息2。这个统计类还处理统计的序列化和反序列化,尽管它不是必须的。
我还创建了一个特殊的 HighScore
class处理可以重置的值,但我仍然想知道曾经存储的“最佳”值是多少。
不是说我的代码是最好的,只是这些是你需要遵循的原则。
1 静态字段也让我可以从任何地方访问这些属性。
2 所有这些仍然是这个特定项目的游戏状态值,但如果我要更改场景,它们仍然会存在
我是一名优秀的程序员,十分优秀!