Unity封裝延時調用定時器
更新時間:2020年04月18日 08:45:33 作者:林新發(fā)
這篇文章主要為大家詳細介紹了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);
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:

