欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Unity封装延时调用定时器

程序员文章站 2024-02-07 20:15:22
本文实例为大家分享了unity封装延时调用定时器的具体代码,供大家参考,具体内容如下封装一个延时调用定时器类using system.collections;using system.collecti...

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

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