public class TestTimer : MonoBehaviour
{
//时间间隔5秒
System.Timers.Timer tt = new System.Timers.Timer(5000);
public Button StartBtn, StopBtn;
private void Start()
{
//绑定执行事件
tt.Elapsed += new System.Timers.ElapsedEventHandler(TestFun);
//True:每隔5秒执行一次,False: 只执行一次
tt.AutoReset = true;
}
public void StartFun()
{
tt.Enabled = true;
tt.Start();
}
private void TestFun(object sender, ElapsedEventArgs e)
{
Debug.Log("123");
}
public void StopFun()
{
tt.Stop();
}
}

本文介绍如何在Unity游戏开发环境中使用C#编写定时器功能。通过创建一个名为TestTimer的MonoBehaviour类,利用System.Timers.Timer类实现每5秒执行一次的定时任务。代码展示了如何初始化定时器、绑定事件处理器、启用和停止定时器。
407

被折叠的 条评论
为什么被折叠?



