我在Update
方法中到达else语句时遇到问题,我不知道如何使这个时钟停止。S
startTime
以秒为单位。如果你把它定为90.0f
,你将有1.30分钟的时间。问题是我需要在到达0:0.0
时停止这个时钟。
public Text TimerText;
private float startTime = 3.0f;
private bool start = false;
private float _time;
private float _minutes, _seconds;
// Use this for initialization
void Start ()
{
start = false;
startTime = 3.0f;
}
// Update is called once per frame
void Update ()
{
// if (start)
// return;
if (startTime > 0.0f)
{
_time = startTime - Time.time; // ammount of time since the time has started
_minutes = (int)_time / 60;
_seconds = _time % 60;
TimerText.text = _minutes + ":" + _seconds.ToString("f1");
}
else
Debug.Log("we are here");
}
private void CheckGameOver()
{
Debug.Log("gameover");
}
public void StartTime()
{
TimerText.color = Color.black;
start = true;
}
使用Time.deltaTime
而不是Time.time
并更改:
if (_time> 0.0f)
{...}
将_time = startTime
添加到Start()
建议像Pawel在回答中那样使用Time.deltaTime
。
我知道这个问题已经解决了,但如果你想知道你的代码为什么不工作,那是因为当你做if (startTime > 0.0f)
时,你应该在if语句中递减startTime
。如果不这样做,startTime>0
将始终是true
,这意味着If语句将永远运行。
您仍然可以通过将if (startTime > 0.0f)
替换为if (Time.time < startTime)
来解决此问题。你不需要再递减了,但它会起作用的。