不算上 C# 自帶的,目前知道兩種,以下分別介紹。
1、每幀檢查
定義一個時間變量 timer,每幀將此時間減去幀間隔時間 Time.deltaTime,如果小於或者等於零,說明定時器到了,執行相應功能代碼,將此定時器重置,代碼如下:
public float timer = 1.0f; // Update is called once per frame void Update() { timer -= Time.deltaTime; if (timer <= 0) { Debug.Log(string.Format("Timer1 is up !!! time=${0}", Time.time)); timer = 1.0f; } }
2、利用協程
在協程中返回需要等待的時間,直接看代碼便明白:
// Use this for initialization void Start() { StartCoroutine(Timer()); } IEnumerator Timer() { while (true) { yield return new WaitForSeconds(1.0f); Debug.Log(string.Format("Timer2 is up !!! time=${0}", Time.time)); } }
3、延遲調用
使用 MonoBehaviour.Invoke,兩個參數,分別是要調用的方法名和延時調用的時間。代碼如下:
// Use this for initialization void Start() { Invoke("Timer", 1.0f); } void Timer() { Debug.Log(string.Format("Timer3 is up !!! time=${0}", Time.time)); Invoke("Timer", 1.0f); }