【Unity】制作一个C#实现的计时器

2021/02/07 07:30
阅读数 208

 

 

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class TimerItem
{
    public int id;
    public float interval;
    public int loopTimes;
    
    public UnityEngine.Object callbackObject;
    public object[] args;

    public Action callback;
    public Action<UnityEngine.Object> callbackObjectEvent;
    public Action<UnityEngine.Object, object[]> callbackObjAndArgs;
    public bool isNotLimtied;
    public bool isStop;

    private float _interval;

    

    public TimerItem(int id,  float interval, int loopTimes, Action action)
    {
        this.interval = interval;
        this.loopTimes = loopTimes;
        this.callback = action;
        isStop = false;
        _interval = this.interval;
        isNotLimtied = loopTimes == -1;
    }
    public TimerItem(int id, float interval, int loopTimes, Action<UnityEngine.Object> action, UnityEngine.Object obj)
    {
        this.interval = interval;
        this.loopTimes = loopTimes;
        this.callbackObjectEvent = action;
        this.callbackObject = obj;
        isStop = false;
        _interval = this.interval;
        isNotLimtied = loopTimes == -1;
    }
    public TimerItem(int id, float interval, int loopTimes, Action<UnityEngine.Object, object[]> action, UnityEngine.Object obj, object[] args)
    {
        this.interval = interval;
        this.loopTimes = loopTimes;
        this.callbackObjAndArgs = action;
        this.callbackObject = obj;
        this.args = args;
        isStop = false;
        _interval = this.interval;
        isNotLimtied = loopTimes == -1;
    }

    public void Reset()
    {
        this.interval = _interval;
        loopTimes--;
    }
}

public class TimerManager
{
    private Dictionary<int, TimerItem> _timerDicti;
    public int actionIndex;
    public TimerManager()
    {
        _timerDicti = new Dictionary<int, TimerItem>();
        actionIndex = 0;
    }
    /// <summary>
    /// 添加一个计时器,返回计时器的 ID
    /// </summary>
    /// <param name="interval">时间间隔</param>
    /// <param name="loopTimes">执行次数,-1表示无限执行</param>
    /// <param name="callback">执行函数</param>
    /// <returns></returns>
    public int AddTimer(float interval, int loopTimes, Action callback)
    {
        TimerItem item = new TimerItem(actionIndex, interval, loopTimes, callback);
        actionIndex++;
        if (!_timerDicti.ContainsKey(actionIndex))
        {
            _timerDicti.Add(actionIndex, item);
        }
        return actionIndex;
    }
    /// <summary>
    /// 添加一个计时器,返回计时器的 ID
    /// </summary>
    /// <param name="interval">时间间隔</param>
    /// <param name="loopTimes">执行次数,-1表示无限执行</param>
    /// <param name="callback">执行函数</param>
    /// <returns></returns>
    public int AddTimer(float interval, int loopTimes, Action<UnityEngine.Object> action, UnityEngine.Object obj)
    {
        TimerItem item = new TimerItem(actionIndex, interval, loopTimes, action, obj);
        actionIndex++;
        if (!_timerDicti.ContainsKey(actionIndex))
        {
            _timerDicti.Add(actionIndex, item);
        }
        return actionIndex;
    }
    /// <summary>
    /// 添加一个计时器,返回计时器的 ID
    /// </summary>
    /// <param name="interval">时间间隔</param>
    /// <param name="loopTimes">执行次数,-1表示无限执行</param>
    /// <param name="callback">执行函数</param>
    /// <returns></returns>
    public int AddTimer(float interval, int loopTimes, Action<UnityEngine.Object, object[]> action, UnityEngine.Object obj, object[] args)
    {
        TimerItem item = new TimerItem(actionIndex, interval, loopTimes, action, obj, args);
        actionIndex++;
        if (!_timerDicti.ContainsKey(actionIndex))
        {
            _timerDicti.Add(actionIndex, item);
        }
        return actionIndex;
    }

    public void Update(float intervalTime)
    {
        for (int i = 0; i < _timerDicti.Count;)
        {
            KeyValuePair<int, TimerItem> item = _timerDicti.ElementAt(i);
            i++;
            if (!item.Value.isStop)
            {
                if (item.Value.isNotLimtied || item.Value.loopTimes > 0)
                {
                    item.Value.interval -= intervalTime;
                    if (item.Value.interval <= 0)
                    {
                        if (item.Value.callback != null)
                        {
                            item.Value.callback();
                        }
                        if (item.Value.callbackObjectEvent != null && item.Value.callbackObject != null)
                        {
                            item.Value.callbackObjectEvent(item.Value.callbackObject);
                        }
                        if (item.Value.callbackObjAndArgs != null && item.Value.callbackObject != null && item.Value.args != null)
                        {
                            item.Value.callbackObjAndArgs(item.Value.callbackObject, item.Value.args);
                        }
                        item.Value.Reset();
                    }
                }
                else
                {
                    i--;
                    _timerDicti.Remove(item.Key);
                }
            }
        }
    }

    public void StopTimerById(int id, bool isStop = true)
    {
        if (_timerDicti.ContainsKey(id))
        {
            _timerDicti[id].isStop = isStop;
        }
    }

    public void RemoveTimerById(int id)
    {
        if (_timerDicti.ContainsKey(id))
        {
            _timerDicti.Remove(id);
        }
    }
}

 

 

测试代码:


public class Core
{

    public static TimerManager _timerManager;
    public static TimerManager TimerManager
    {
        get
        {
            if(_timerManager == null)
            {
                _timerManager = new TimerManager();
            }
            return _timerManager;
        }
    }
}

public class Test : MonoBehaviour
{
     int index1;
    int index2;

    int id = 0;
    private void Awake()
    {

        object[] args = new object[3];
        args[0] = 1324;
        args[1] = 13232134;
        args[2] = 56565;
        int id = Core.TimerManager.AddTimer(1, -1, TimerTest1);
        Core.TimerManager.AddTimer(3, 2, TimerTest2, this.gameObject);
        Core.TimerManager.AddTimer(10, 2, TimerTest3, this.gameObject, args);
    }
    private void OnDestroy()
    {
        Core.TimerManager.RemoveTimerById(id);
    }

    private void TimerTest1()
    {
        Debug.LogError(++index1);
    }

    private void TimerTest2(UnityEngine.Object obj)
    {
        Debug.LogError(obj.name + (++index2));
    }

    private void TimerTest3(UnityEngine.Object obj, object[] args)
    {
        for (int i = 0; i < args.Length; i++)
        {
            Debug.LogError(args[i].ToString() + obj.name);
        }
    }
   private void FixedUpdate()
    {
        Core.TimerManager.Update(Time.fixedDeltaTime);
    }
}

 

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部