计时器,从0开始到第10秒结束,第10秒后计时器应该变为0
本文关键字:计时器 10秒 结束 开始 | 更新日期: 2023-09-27 18:03:41
if (coinMag == true)
{
Timer += 1 * Time.deltaTime;
if (Timer >= 10)
{
coinMag = false;
Timer = 0;
}
}
我想要的是当CoinMag是真的计时器应该开始…我已经初始化定时器作为公共浮动Timer=0.0f
;..当计时器在10秒后启动时,计时器应该重新初始化为0。
使用此coroutine
:
IEnumerator Timer(float duration,Action callBack = null)
{
float elapsedTime = 0.0f;
while (elapsedTime < duration)
{
yield return null;
elapsedTime += Time.deltaTime ;
}
if (callBack != null)
{
callBack();
}
}
:
StartCoroutine(Timer(10,()=>{Debug.Log("After 10 seconds");}));
如果您需要公开计时器值(除了在计时器到期时运行一个方法之外),您可以这样做:
private BackgroundWorker timer = new BackgroundWorker();
public void initialize()
{
timer.DoWork += doTimer;
timer.RunWorkerAsync();
}
public double milliseconds_Remaining = 0;
public double milliseconds_Transpired = 0;
private void doTimer(object sender, DoWorkEventArgs e)
{
bool isRunning = true;
DateTime begin = DateTime.Now;
while (isRunning)
{
//update times
double milliseconds = DateTime.Now.Subtract(begin).TotalMilliseconds;
milliseconds_Remaining = 10000 - milliseconds;
milliseconds_Transpired = milliseconds;
if (milliseconds >= 10000)
{
//activate timer function
//reset
begin = DateTime.Now;
}
System.Threading.Thread.Sleep(250);//or 500 or 50 depending on accuracy needed
}
}