1. 程式人生 > 程式設計 >Unity封裝延時呼叫定時器

Unity封裝延時呼叫定時器

本文例項為大家分享了Unity封裝延時呼叫定時器的具體程式碼,供大家參考,具體內容如下

封裝一個延時呼叫定時器類

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class WaitTimeManager 
{
 private static TaskBehaviour m_Task;
 static WaitTimeManager()
 {
 GameObject go = new GameObject("#WaitTimeManager#");
 GameObject.DontDestroyOnLoad(go);
 m_Task = go.AddComponent<TaskBehaviour> ();
 }

 //等待
 static public Coroutine WaitTime(float time,UnityAction callback)
 {
 return m_Task.StartCoroutine(Coroutine(time,callback));
 }
 
 //取消等待
 static public void CancelWait(ref Coroutine coroutine)
 {
 if (coroutine != null) {
 m_Task.StopCoroutine(coroutine);
 coroutine = null;
 }
 }

 static IEnumerator Coroutine(float time,UnityAction callback) {
 yield return new WaitForSeconds (time);
 if (callback != null) {
 callback();
 }
 }
 
 //內部類
 class TaskBehaviour : MonoBehaviour { }
}

測試

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Script_04_15 : MonoBehaviour {

 void Start () {
 //開啟定時器
 Coroutine coroutine = WaitTimeManager.WaitTime(5f,delegate {
 Debug.LogFormat("等待5秒後回撥");
 });

 //等待過程中取消它
 //WaitTimeManager.CancelWait (ref coroutine);
 }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。