unity自制延迟定时回调

如下:

using UnityEngine;
using System.Collections;

public class DelayCallCtrler :MonoBehaviour
{
    private static DelayCallCtrler s_instance = null;
    private static DelayCallCtrler GetInstance()
    {
        if (null == s_instance)
        {
            GameObject go = new GameObject("DelayCallCtrler");
            s_instance = go.AddComponent();
        }
        return s_instance;
    }

    private BehavTimer m_invoke_timer = new BehavTimer();

    public static void Call(System.Action func, float delay)
    {
        if (null == func) return;
        if (0 > delay)
        {
            func(); 
            return;
        }
        var instance = GetInstance();
        instance.enabled = true;
        instance.m_invoke_timer.Invoke(func, delay);
    }

    public static void Clear()
    {
        var instance = GetInstance();
        instance.m_invoke_timer.Clear();
        instance.enabled = false;
    }

    protected void Update()
    {
        m_invoke_timer.Update(Time.deltaTime);
        if (m_invoke_timer.count <= 0)
        {
            enabled = false;
        }
    }
}

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

public class TimerData
{
    public float time;
    public System.Action cb;
}

public class BehavTimer 
{
    private List m_list = new List();
    private float m_dt = 0;

    public int count { get { return m_list.Count; } }

    public void Invoke(System.Action cb,float delay)
    {
        if (null == cb) return;
        m_list.Add(new TimerData() { cb = cb, time = delay });
    }

    public void Clear()
    {
        m_list.Clear();
    }

    public void Update(float dt)
    {
        if (m_list.Count <= 0) return;
        m_dt = dt;
        m_list.ForEach(UpdateData);
        m_list.RemoveAll(RemoveDataCdt);
    }

    static bool RemoveDataCdt(TimerData td)
    {
        return td.time < 0;
    }

    protected void UpdateData(TimerData td)
    {
        td.time -= m_dt;
        if (td.time <= 0)
        {
            if (null != td.cb)
            {
                td.cb();
            }
        }
    }
}


你可能感兴趣的:(unity自制延迟定时回调)