【问题标题】:Saving and loading high scores in Unity2d在 Unity2d 中保存和加载高分
【发布时间】:2015-09-08 19:11:02
【问题描述】:

到目前为止我所做的是在游戏中设置一个分数以每秒增加一个分数,让分数显示在游戏场景中,然后如果分数大于高分,则将高分设置为等于分数.到目前为止,这是我的代码:

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;

        }} }

当这段代码发生时,“游戏结束”等于真:

void OnCollisionEnter2D (Collision2D col) {

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

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

    }

我想要的是此时(当对象发生碰撞并且游戏结束时)以保存分数,然后加载游戏结束场景。如何在游戏结束时保存分数,然后将其与保存的高分一起加载到游戏结束场景中??

【问题讨论】:

    标签: c# android unity3d-2dtools


    【解决方案1】:

    有多种方法可以做到这一点,如果您只保留该会话的分数,最明显的两种方法是将其存储在 静态类单身。无论场景加载如何,这些类都将持续存在多久,因此请注意如何管理其中的信息。

    静态类实现的一个例子是:

    public static class HighScoreManager
    {
        public static int HighScore { get; private set; }
    
        public static void UpdateHighScore(int value)
        {
            HighScore = value;
        }
    }
    

    如果您希望将数据保留更长时间,您需要查看this

    我希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 2023-03-20
      相关资源
      最近更新 更多