当前位置 : 主页 > 网络编程 > c#编程 >

Unity封装延时调用定时器

来源:互联网 收集:自由互联 发布时间:2020-11-08
本文实例为大家分享了Unity封装延时调用定时器的具体代码,供大家参考,具体内容如下 封装一个延时调用定时器类 using System.Collections;using System.Collections.Generic;using UnityEngine;using Unit

本文实例为大家分享了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);
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

网友评论