Invoke和InvokeRepeating是MonoBehaviour中的两个内置延时方法
- Invoke
Invoke(methodName:string, time:float): void;
methodName:方法名
time:多少秒之后执行
- InvokeRepeating
InvokeRepeating(methodName: string, time: float, repeatRate: float): void
methodName:方法名
time:多少秒之后执行
repeatRate:重读执行间隔
- IsInvoking: 用来判断某方法是否被延迟,即将执行
- CancelInvoke: 取消该脚本上所有的延时方法
代码演示:
public class TestInvoke : MonoBehaviour
{
private float nowTime;
private int count;
void Start()
{
nowTime = Time.time;
Debug.Log("时间点:" + nowTime);
Invoke("setTimeOut", 3f);
InvokeRepeating("setTimeRepeat", 2f, 1f);
}
private void setTimeOut()
{
nowTime = Time.time;
Debug.Log("执行延时方法: " + nowTime);
}
private void setTimeRepeat()
{
nowTime = Time.time;
Debug.Log("执行重复方法: " + nowTime);
count += 1;
if (count == 10)
{
CancelInvoke();
}
}
}
运行结果: