Unity_计时器实现的四种方式

在Unity中,有许多种实现计时器的方式,以下是其中一些常用的方法:

1.使用Time.deltaTime

在Unity中,可以使用Time.deltaTime来计算游戏运行的时间。可以在每一帧的Update()函数中使用它,将它乘以一个时间因子,得到累计的时间。例如:

public float time;
void Update() {
    time += Time.deltaTime;
}

2. 使用Coroutine,也就是我们的协程,使用协程很简单,见之前发的博客:

相信系统学习过Unity的人都听说过协程,使用协程可以轻而易举的来实现计时的操作

using UnityEngine;

public class TimerExample : MonoBehaviour
{
    public float delayTime = 3f;

    private void Start()
    {
        StartCoroutine(StartTimer());
    }

    private IEnumerator StartTimer()
    {
        yield return new WaitForSeconds(delayTime);
        // 在此处添加计时器结束后要执行的代码
        Debug.Log("Timer finished!");
    }
}

3.使用InvokeRepeating函数:

Unity中的InvokeRepeating函数可以在一定时间间隔内重复调用一个函数。例如:

public float time;
void Start() {
    InvokeRepeating("IncrementTime", 1f, 1f);
}
void IncrementTime() {
    time++;
}

4.使用Timer类:

Timer类是.NET Framework中的一个类,可以在Unity中使用。可以使用Timer类来实现计时器。例如:

using System.Timers;
public float time;
void Start() {
    Timer timer = new Timer(1000);
    timer.Elapsed += IncrementTime;
    timer.AutoReset = true;
    timer.Enabled = true;
}
void IncrementTime(object sender, ElapsedEventArgs e) {
    time++;
}

这些都是常见的计时器实现方式,具体选择哪种方式,要根据实际需求和场景来决定。

猜你喜欢

转载自blog.csdn.net/m0_69778537/article/details/130299794
今日推荐