1. 程式人生 > >U3D Invoke系列函數

U3D Invoke系列函數

cti ali gin ati http int () 分享 2.4

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方法的延時

U3D Invoke系列函數