Unity Invoke以及InvokeRepeating延时函数用法

元气小坏坏 提交于 2019-11-27 00:52:22

InvokeInvokeRepeating是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();
        }
    }
}

运行结果:
在这里插入图片描述
在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!