[英]Saving and loading high scores in Unity2d
到目前為止,我所做的是設置一個分數,使其在游戲中每秒增加一次,讓該分數顯示在游戲場景中,然后如果分數大於最高分數,則將最高分數設置為等於該分數。 到目前為止,這是我的代碼:
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;
}} }
發生以下代碼時,“游戲結束”等於true:
void OnCollisionEnter2D (Collision2D col) {
if (col.gameObject.tag == "enemyPlanet") {
ui.gameOverActivated ();
Destroy (gameObject);
Application.LoadLevel ("gameOverScene2");
}
}
我想要的是在這一點上(當對象碰撞並且游戲結束為真時)保存分數,然后加載游戲結束場景。 如何在比賽結束時保存分數,然后將其與保存的高分一起載入游戲現場?
有多種方法可以執行此操作,如果僅保留該會話的分數,則最明顯的兩種方法是將其存儲在Static Class或Singleton中 。 無論需要何種場景加載,這些類都將持續存在很長時間,無論場景加載如何,因此請注意如何管理其中的信息。
靜態類實現的一個示例是:
public static class HighScoreManager
{
public static int HighScore { get; private set; }
public static void UpdateHighScore(int value)
{
HighScore = value;
}
}
如果您正在尋找將持續更長的時間量的數據,你需要看看這個
我希望這有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.