unity延時方法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:取消該腳本上的所有延時方法

下面是代碼筆記:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM