-----------------------原生------------------------
void Start()
{
StartCoroutine(零点五秒后执行());
}
IEnumerator 零点五秒后执行()
{
yield return new WaitForSeconds(0.5f);
//TODO:执行体
}
还用一种方法是在void FixedUpdate()中执行
-----------------------自定义-------------------------
声明:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Timer
{
/// <summary>
/// 时间间隔(秒)
/// </summary>
private double m_interval;
/// <summary>
/// 可运行时间
/// </summary>
private DateTime m_runTime;
/// <summary>
/// 初始化
/// </summary>
/// <param name="interval">时间间隔</param>
/// <param name="runNow">是否立即运行</param>
public Timer(double interval = 1, bool runNow = true)
{
m_interval = interval;
if (runNow)
m_runTime = DateTime.Now;
else
m_runTime = DateTime.Now.AddSeconds(m_interval);
}
/// <summary>
/// 是否可运行
/// </summary>
public bool Run
{
get
{
if (m_runTime > DateTime.Now)
return false;
else
{
m_runTime = DateTime.Now.AddSeconds(m_interval);
return true;
}
}
}
}
使用:
private Timer m_timer = new Timer(0.02);
// Update is called once per frame
void Update()
{
if (m_timer.Run)
{
//TODO;需要做的事情
}
}