U3D Invoke系列函数

public void Invoke(string methodName, float time)

  多少秒后执行某个函数

  参数说明:

    methodName:要执行的函数的名称

    time:秒数,time秒后执行methodName函数

void Start ()
    {
        Invoke("CreatBoxFun", 5f);  //延时5秒后执行CreateBoxFun()函数  
    }
    
    
    void CreatBoxFun()
    {        
            GameObject.Instantiate(obj, new Vector3(Random.Range(-10.14f, 11.51f), 8f, Random.Range(-12.46f, 11.49f)), Quaternion.identity);       
    }

public void InvokeRepeating(string methodName, float time, float repeatRate) 

  多少秒[第二个参数]后执行某个函数,并且以后每隔多少秒[第三个参数]都会执行该函数一次[重复调用N次]。

  参数说明:

    methodName:方法名
    time:多少秒后执行
    repeatRate:重复执行间隔
using UnityEngine;
using System.Collections;

public class DelayScript : MonoBehaviour {
    //当前时间
    private float nowTime;
    //执行重复方法的次数
    private int count;
    // Use this for initialization
    void Start () {
        nowTime = Time.time;
        Debug.Log("时间点:"+nowTime);
        this.Invoke("setTimeOut", 3.0f);
        this.InvokeRepeating("setInterval", 2.0f, 1.0f);
    }

    private void setTimeOut()
    {
        nowTime = Time.time;
        Debug.Log("执行延时方法:" + nowTime);
    }

    private void setInterval()
    {
        nowTime = Time.time;
        Debug.Log("执行重复方法:" + nowTime);
        count += 1;
        if(count==5)
            this.CancelInvoke();
    }
}

Invoke和InvokeRepeating为延时方法

public bool IsInvoking()

  判断是否有方法被延时,它还有一个重载:public bool IsInvoking(string methodName) 它是判断是否有名为methodName的方法被延时

  参数说明:

    methodName:需要被判断是否延时的函数名

 void Start()
    {
        InvokeRepeating("Move", 0.3f, 0.3f);
        Invoke("cancle", 5f);            
    }

    void cancle()
    {
        if(IsInvoking("Move"))
            CancelInvoke();
    }

 public void CancelInvoke()

  取消该脚本上的所有延时方法

 public GameObject obj;
 
    void Start ()
    {
        InvokeRepeating("CreatBoxFun", 5f, 5f);
        Invoke("cancelInvoke", 21f);
    }
    void cancelInvoke()
    {
        CancelInvoke();
    }
    
    void CreatBoxFun()
    {        
            GameObject.Instantiate(obj, new Vector3(Random.Range(-10.14f, 11.51f), 8f, Random.Range(-12.46f, 11.49f)), Quaternion.identity);       
    }

  它有一个重载,public void CancelInvoke(string methodName),取消名为methodName方法的延时

原文地址:https://www.cnblogs.com/forever-Ys/p/10373965.html