定时器

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class WaitTimeManager : MonoBehaviour
{
    private static TaskBehaviour m_Task;

    static WaitTimeManager()
    {
        GameObject go = new GameObject("#WaitTimeManager#");
        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 CancleWait(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 { }
}


调用:

Coroutine coroutine = WaitTimeManager.waitTime(5f, delegate ()
        {
            Debug.Log("等待五秒回调");
        });
posted @ 2022-02-21 17:45  小帆敲代码  阅读(21)  评论(0编辑  收藏  举报