unity简单示例——延迟操作-定时器

    科技2024-04-23  76

    不依赖于脚本实现的定时器

    using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; /**************************************************** 作者:cg 功能:延迟一定时间后执行 *****************************************************/ public class WaitTimeManager { private static TaskBehaviour m_task; static WaitTimeManager() { GameObject go = new GameObject("#WaitTimeManager#"); GameObject.DontDestroyOnLoad(go); m_task = go.AddComponent<TaskBehaviour>(); } public static Coroutine WaitTime(float time,UnityAction action) { return m_task.StartCoroutine(CustomCoroutine(time, action)); } public static void Cancel(ref Coroutine coroutine) { if(coroutine!=null) { m_task.StopCoroutine(coroutine); coroutine = null; } } static IEnumerator CustomCoroutine(float time,UnityAction callback) { yield return new WaitForSeconds(time); if(callback!=null) { callback(); } } class TaskBehaviour : MonoBehaviour { } }

    可循环隔一定时间间隔调用定时器

    class TaskIntervalBehaviour : MonoBehaviour { IEnumerator Start() {//可以循环调用,利用Start自己开始 //十秒后结束 yield return new CustomWait(10f, 1f, delegate () { Debug.LogFormat("每过一秒回调一次 :{0}", Time.time); }); Debug.Log("十秒结束"); } public class CustomWait : CustomYieldInstruction { public override bool keepWaiting { get { //此方法返回false表示协程结束 if (Time.time - m_StartTime >= m_Time) { return false; } else if (Time.time - m_LastTime >= m_Interval) { //更新上一次间隔时间 m_LastTime = Time.time; m_IntervalCallback(); } return true; } } private UnityAction m_IntervalCallback; private float m_StartTime; private float m_LastTime; private float m_Interval; private float m_Time; public CustomWait(float time, float interval, UnityAction callback) { //记录开始时间 m_StartTime = Time.time; //记录上一次间隔时间 m_LastTime = Time.time; //记录间隔调用时间 m_Interval = interval; //记录总时间 m_Time = time; //间隔回调 m_IntervalCallback = callback; } } }

     

    Processed: 0.024, SQL: 9