2015-09-08 32 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

我希望这有助于!