在Unity2d中保存和加载高分
本文关键字:加载 保存 Unity2d | 更新日期: 2023-09-27 18:12:00
到目前为止,我所做的是设置一个分数,在游戏玩法中每秒钟增加一个分数,让分数显示在游戏场景中,然后设置最高分等于分数,如果分数大于最高分。这是我到目前为止的代码:
bool gameOver;
public Text scoreText;
public Text highScoreText;
int score;
int highScore;
// Use this for initialization
void Start () {
score = 0;
highScore = 0;
InvokeRepeating ("scoreUpdate", 1.0f, 1.0f);
gameOver = false;
}
// Update is called once per frame
void Update () {
scoreText.text = "★" + score;
highScoreText.text = "★" + highScore;
}
public void gameOverActivated() {
gameOver = true;
if (score > highScore) {
highScore = score;
}
PlayerPrefs.SetInt("score", score);
PlayerPrefs.Save();
PlayerPrefs.SetInt("highScore", highScore);
PlayerPrefs.Save();
}
void scoreUpdate() {
if (!gameOver) {
score += 1;
}} }
"game over" = true
void OnCollisionEnter2D (Collision2D col) {
if (col.gameObject.tag == "enemyPlanet") {
ui.gameOverActivated ();
Destroy (gameObject);
Application.LoadLevel ("gameOverScene2");
}
}
我想要的是在这一点上(当物体碰撞和游戏结束是真的),分数被保存,然后游戏结束场景被加载。我如何在游戏结束时保存分数,然后将它与保存的高分一起加载到游戏结束场景中?
有多种方法可以做到这一点,如果您只持久化该会话的分数,最明显的两种方法是将其存储在静态类或Singleton中。无论你需要这些类多长时间,它们都将持续存在,无论场景加载如何,所以要小心如何管理它们中的信息。
静态类实现的一个例子是:public static class HighScoreManager
{
public static int HighScore { get; private set; }
public static void UpdateHighScore(int value)
{
HighScore = value;
}
}
如果您希望将数据持久化更长时间,则需要查看此
我希望这对你有帮助!