C# 创建类似Time.Time的计时器,但可以将其重置为0

C# 创建类似Time.Time的计时器,但可以将其重置为0,c#,unity3d,C#,Unity3d,我能做一个计时器或以某种方式重置时间吗?我试过做这个 float Timer(float time) { if (Time.time > nextTime) { return 0.01f; nextTime = Time.time + 0.01f; } else { return 0; } } 但它

我能做一个计时器或以某种方式重置时间吗?我试过做这个

    float Timer(float time)
    {
        if (Time.time > nextTime)
        {
            return 0.01f;
            nextTime = Time.time + 0.01f;
        }
        else
        {
            return 0;
        }
    }

但它似乎不能正常工作,时间和时间不一样。时间可以这样创建计时器

  public float timeLeft=5f;

     void FixedUpdate()
     {
         timeLeft -= Time.deltaTime;
         if(timeLeft < 0)
         {
             DoSomething();
             timeLeft=5f; //If you want to reset timer 
         }
     }
public float timeLeft=5f;
void FixedUpdate()
{
timeLeft-=Time.deltaTime;
如果(时间间隔<0)
{
DoSomething();
timeLeft=5f;//如果要重置计时器
}
}

或者您可以始终使用协同程序“yield return new WaitForSeconds(5f);”

Time。Time
是自游戏启动以来经过的秒数。这不是你应该重新设置的东西。创建您自己的浮点变量,并在
Update
循环中将其递增
Time.deltaTime
,然后将其重置。计时器无法重置为0。它只是被设置成和时间一样
public class Timer : MonoBehaviour
{
    private static float _lastTime = Time.realtimeSinceStartup;

    [SerializeField, Tooltip("Time in second between timer ding dong."), Range(0f, 3600f)]
    private float _interval = 5f;

    public UnityEvent OnTickTack;

    private void Update()
    {
        if (Time.realtimeSinceStartup - _lastTime >= _interval)
        {
            _lastTime = Time.realtimeSinceStartup;
            OnTickTack.Invoke();
        }
    }
}