Example #1
0
    void Update()
    {
        #region 0's
        float t  = Time.time;
        float rt = Time.realtimeSinceStartup;
        if (Timers.Count > 0)
        {
            float compareTime = 0;
            bool  ok          = false;
            for (int i = Timers.Count - 1; i >= 0; i--)
            {
                if (i >= Timers.Count)
                {
                    continue;
                }
                UTimer timer = Timers[i];
                compareTime = timer.ignoreTimeScale ? rt : t;
                ok          = (compareTime - timer.time) >= timer.delay;
                if (ok && (timer.loop == 0 || timer.count < timer.loop))
                {
                    timer.count++;
                    timer.time += timer.delay;

                    if (timer.loop != 0 && timer.loop <= timer.count)
                    {
                        Timers.RemoveAt(i);
                    }

                    try
                    {
                        if (timer.args == null && timer.simpleAction != null)
                        {
                            timer.simpleAction();
                        }
                        else
                        {
                            timer.action(timer.args);
                        }
                    }catch (Exception ex)
                    {
                        Log.Exception(ex);
                    }
                }
            }
        }

        #endregion

        #region 1's
        if (0 == _timerMap.Count)
        {
            return;
        }

        if (0 != _cachedKeyList.Count)
        {
            _cachedKeyList.Clear();
        }

        var iter = _timerMap.GetEnumerator();
        while (iter.MoveNext())
        {
            _cachedKeyList.Add(iter.Current.Key);
        }
        //for (int i = 0; i < _timerKeyList.Count; ++i)   // 缓存键名处理,为了防止在回调中做了定时器的增减操作
        //    _cachedKeyList.Add(_timerKeyList[i]);

        for (int i = 0; i < _cachedKeyList.Count; ++i)
        {
            string keyItem = _cachedKeyList[i];

            if (!_timerMap.ContainsKey(keyItem))
            {
                continue;
            }

            TimerInfo timerInfo = _timerMap[keyItem];
            timerInfo._time -= Time.deltaTime;
            if (timerInfo._time > 0)
            {
                continue;
            }

            _timerMap.Remove(keyItem);  // 必须前置,后置会导致嵌套调用tierm重复删除相关键名

            if (null != timerInfo._callback)
            {
                timerInfo._callback(timerInfo._param);
            }
        }
        #endregion
    }