我的倒计时器发生了一些奇怪的事情,我卡住了。我将一个数字传递给我的计时器(15秒),它从15开始,然后跳到0,然后从那里倒数:0,-1,-2,-3……我在这里做错了什么?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CountdownTimer : MonoBehaviour
{
float seconds;
public Text timerText;
public void Update()
{
seconds -= Time.deltaTime;
if (timerText != null)
{
timerText.text = Mathf.Round(seconds).ToString();
Debug.Log (Mathf.Round(seconds));
}
}
}我从另一个脚本中的函数调用倒计时脚本,如下所示:
void ShowRestartWarning()
{
//Debug.Log("Restart Warning Dialog");
canvas = GameObject.FindGameObjectWithTag("Canvas");
timerInstance = Instantiate(timeOutWarningDialog);
timerInstance.transform.SetParent(canvas.transform, false);
timerInstance.SetActive(true);
CountdownTimer countdownTimer = timeOutWarningDialog.GetComponent<CountdownTimer>();
countdownTimer.Update();
CancelInvoke();
Invoke("RestartGame", countdownLength);
}发布于 2017-06-13 06:18:19
尝试使用协程而不是Update函数,这样您就可以随时启动和停止它。
public Text timerText;
public void Start(int seconds)
{
StartCoroutine("RunTimer", seconds);
}
IEnumerator RunTimer(int seconds)
{
while (seconds > 0)
{
if (timerText != null)
{
timerText.text = seconds.ToString();
Debug.Log (seconds);
}
yield return new WaitForSeconds(1);
seconds -= 1;
}
}https://stackoverflow.com/questions/44500002
复制相似问题