2015-09-08 41 views
0

我到目前爲止所做的是在遊戲中設置每秒增加的分數,獲得在遊戲場景中顯示的分數,然後設置高分等於分數if得分高於高分。這是到目前爲止我的代碼:在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; 

     }} } 

「GAME OVER」等於真當此代碼發生:

void OnCollisionEnter2D (Collision2D col) { 

     if (col.gameObject.tag == "enemyPlanet") { 

      ui.gameOverActivated(); 
      Destroy (gameObject); 
      Application.LoadLevel ("gameOverScene2"); 
     } 

    } 

我想在這一點上(當物體發生碰撞和遊戲結束是真),以保存分數,然後加載場景上的遊戲。如何在比賽結束時保存比分,然後將比賽中的比分加載到場上以及保存的比分?

回答

1

有多種方法可以做到這一點,兩個最明顯的方式做到這一點,如果你只堅持該會話的比分是將其存儲在一個靜態類辛格爾頓。無論場景加載如何,這些類都會持續很長時間,因此請小心如何管理它們中的信息。

靜態類實現的一個例子是:

public static class HighScoreManager 
{ 
    public static int HighScore { get; private set; } 

    public static void UpdateHighScore(int value) 
    { 
     HighScore = value; 
    } 
} 

如果您正在尋找持久化數據的一段較長的時間,你需要看this

我希望這有助於!