【问题标题】:PlayerPrefs for score in dynamically loaded levelsPlayerPrefs 用于动态加载关卡中的得分
【发布时间】:2018-07-09 19:11:55
【问题描述】:

我在 Unity 中创建了一个破砖游戏,其中一个名为 Game 的场景根据从 json 文件接收到的数据加载每个关卡。

IE:

  • 一旦所有砖块从 1 级被摧毁,第二级是 加载到同一个场景中,依此类推。
  • 一旦您输了,“输”场景会加载一个“再玩”按钮。

我希望高分信息保留在播放器首选项中,即使在您按下“再次播放”按钮后也是如此。

但我对它的工作原理有点困惑。这是我的得分代码:

using UnityEngine;
using UnityEngine.UI;

public class Score : MonoBehaviour
{

    public Text scoreText;
    public Text highScoreText;
    private int score;
    private int highScore;

    void Start()
    {
        score = 0;
        GetHighScore();
    }

    void Update()
    {
        UpdateScore();
        SetHighScore();
        GetHighScore();
    }

    // TO UPDATE HIGH SCORE
    void SetHighScore()
    {
        if (score > highScore)
        {
            PlayerPrefs.SetInt("HighScore", score);
        }
    }

    void GetHighScore()
    {
        highScore = PlayerPrefs.GetInt("HighScore");
        highScoreText.text = "High score: " + highScore;
    }
    // TO UPDATE HIGH SCORE

    // TO UPDATE SCORE
    public void AddPoints(int points)
    {
        score = score + points;
        UpdateScore();
    }

    void UpdateScore()
    {
        scoreText.text = "score: " + score;
    }
    // TO UPDATE SCORE
}

到目前为止,分数更新正常,但高分没有任何变化。任何帮助表示赞赏!

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    这里的方法没有任何效果

    void GetHighScore()
    {
        PlayerPrefs.GetInt("HighScore");
    }
    

    应该是

    void GetHighScore()
    {
        highScore = PlayerPrefs.GetInt("HighScore");
    }
    

    我看不出在Update 中的每一帧都调用它的意义。在Start调用一次

    另外,您可能希望在SetHighScore 中更新highScore

    if (score > highScore)
    {
        highScore = score;
        PlayerPrefs.SetInt("HighScore", highScore);
        highScoreText.text = "high score: " + highScore;
    }
    

    【讨论】:

    • 最后一行不会是 "highScoreText.text = "high score: " + highScore; since highScore = score;
    • 好吧,这并不重要,因为 highScore 与 score 具有相同的价值 :) 但我同意当你阅读它时它更有意义
    • 所以我这样做了: // 更新高分 void SetHighScore() { if (score > highScore) { PlayerPrefs.SetInt("HighScore", score); } } void GetHighScore() { highScore = PlayerPrefs.GetInt("HighScore"); highScoreText.text = "高分:" + highScore; } // 更新高分
    • @Frederik 出于某种原因,高分仍然从未改变
    • 你的意思是UI文本没有更新?您是否在 Unity 控制台中遇到任何错误?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    相关资源
    最近更新 更多