Unity封装延时调用定时器的方法

这篇文章主要讲解了Unity封装延时调用定时器的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

目前创新互联已为上1000家的企业提供了网站建设、域名、虚拟主机、网站托管维护、企业网站设计、策勒网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

封装一个延时调用定时器类

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

 //等待
 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);
 }
}

看完上述内容,是不是对Unity封装延时调用定时器的方法有进一步的了解,如果还想学习更多内容,欢迎关注创新互联行业资讯频道。


网页名称:Unity封装延时调用定时器的方法
本文链接:http://ybzwz.com/article/gcecsc.html