【问题标题】:Create highscore value创造高分价值
【发布时间】:2020-11-27 00:13:11
【问题描述】:

我想做一个高分标记,但它的值始终保持在 0。请帮助

using UnityEngine;
using UnityEngine.UI;

public class score : MonoBehaviour {

    public Transform jugador;
    public Text scoreText;
    public Text highScore;

    void Start(){
        highScore.text = PlayerPrefs.GetString ("HighScore", 0);
    }

    void Update () {
        scoreText.text = jugador.position.z.ToString("0");
    }
    public void HighScore(){
        PlayerPrefs.SetString("HighScore", jugador.position.z.ToString("0");
    }
}

【问题讨论】:

  • 您是否尝试过获取和设置浮点数而不是字符串?

标签: c# unity3d


【解决方案1】:

设定分数:

public Text score;
public Text highscore;
private float currentscore = 0;

要提高分数,我们可以简单地将currentscore 设置为当前的position.z,然后更新我们的Text 组件。

增加分数:

private void Update () {
    // Get the current Z position of jugador and round to a whole number.
    currentScore = jugador.position.z;
    // Set our scoreText Component to the currentScore.
    scoreText.text = currentScore.ToString("0");
}

之后,我们使用Score 中的SetHighScore() 方法将高分设置为currentscore

设置高分:

private void SetHighScore() {
   // Set HighScore to the currentScore if it's bigger than the current HighScore.
   if (currentScore > PlayerPrefs.GetFloat("HighScore", 0.0f)) {
       PlayerPrefs.SetFloat("HighScore", currentScore);
   }
}

在我们死后真正看到我们的新乐谱。我们可以使用Start()方法来设置highscore文本。

设置高分文本:

void Start() {
    // Set highscore Text to the current HighScore.
    highscore.text = PlayerPrefs.GetFloat("HighScore", 0.0f).ToString("0");
}

【讨论】:

  • 为什么不使用float 并跳过舍入?
  • 因为它会显示为高分,而浮点数可能是一个有很多小数位的数字。导致得分文本很大,或者您无论如何都需要四舍五入。
  • 不,您只需要使用ToString(format) 并提供您想要在此处显示的所需format,例如ToString("0") OP 有它或 ToString("D") 小数.. 在计算过程中始终使用准确的值而不是四舍五入!
  • 好的,感谢您的提示,将相应地编辑我的答案。
猜你喜欢
  • 2021-10-30
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 2018-08-17
  • 1970-01-01
  • 2018-04-19
相关资源
最近更新 更多