C# 为什么我的代码没有跟踪分数?
我有这个脚本来跟踪我的分数,我把它附加到我的玩家对象上,当然还有我的UI文本对象。我没有任何错误,但是文本没有改变,它保持在0C# 为什么我的代码没有跟踪分数?,c#,unity3d,C#,Unity3d,我有这个脚本来跟踪我的分数,我把它附加到我的玩家对象上,当然还有我的UI文本对象。我没有任何错误,但是文本没有改变,它保持在0 using UnityEngine; using System.Collections; using UnityEngine.UI; public class ScoreTracker : MonoBehaviour { public Text scoreText; static int playerScore = 0; void Sta
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ScoreTracker : MonoBehaviour {
public Text scoreText;
static int playerScore = 0;
void Start () {
scoreText.text = playerScore.ToString ();
}
void Update () {
playerScore += (int)Time.deltaTime;
}
}
Start()代码>在增加分数后如果只增加分数,是否有效
playerscore++;
Time.deltaTime返回的值可能小于1。Update()方法大约每秒调用60次(取决于您的fps设置),并且deltaTime与上次更新调用的时间不同。因此,在大多数情况下,deltaTime
value=1/60,要转换为int,它将始终为0。请尝试以下代码:
public class ScoreTracker : MonoBehaviour
{
public Text scoreText;
static int playerScore = 0;
public int nextScoreAtSecond = 1;
float timeIncrease;
void Start()
{
timeIncrease = 0;
UpdateScore();
}
void Update()
{
timeIncrease += Time.deltaTime;
if (timeIncrease > nextScoreAtSecond)
{
// reset the time counter
timeIncrease = 0;
playerScore = playerScore + 1;
UpdateScore();
}
}
void UpdateScore()
{
scoreText.text = playerScore.ToString();
}
}
当你调用Update()
时,Time.deltaTime
的值是多少?你希望你的分数在游戏过程中每秒钟增加1分吗?@WeryNguyen是的。好吧,比这多了一点,但是的,这是基本的想法。这是一个侧卷轴,只要你没有死,你应该看到计数器上升。是的,我知道,但我试过了,但它不起作用,我真的很困惑。所以试着添加一个实际的int(就像@wvisaacs建议的那样)。deltaTime是一个小浮点,所以当转换为int时,它可能会被截断为0,实际上是这样。但是为什么使用time.deltatime根本不改变数字?@OfficerVimes“time.deltatime可能返回一个小于1的值。”哦,好吧,我只是不知道deltatime到底是如何工作的。非常感谢,我想下次我会先阅读文档。