private TimerRepeatInfo GetFromPool() { TimerRepeatInfo timerRepeatInfo; int count = m_pool.Count; if (count > 0) { timerRepeatInfo = m_pool[count - 1]; m_pool.RemoveAt(count - 1); timerRepeatInfo.isDeleted = false; timerRepeatInfo.Elapsed = 0; } else { timerRepeatInfo = new TimerRepeatInfo(); } return(timerRepeatInfo); }
private void ReturnToPool(TimerRepeatInfo t) { t.Callback = null; m_pool.Add(t); }
void Update() { m_time = Time.time; float elapsed = m_time - m_lastTime; // 判断时间缩放 if (Time.timeScale != 0) { elapsed /= Time.timeScale; } m_lastTime = m_time; foreach (KeyValuePair <TimerCallback, TimerRepeatInfo> kvp in m_items) { TimerRepeatInfo item = kvp.Value; // 处理过期调用 if (item.isDeleted) { m_toRemove.Add(item); continue; } // 处理间隔时间 没到需求的间隔时间 item.Elapsed += elapsed; if (item.Elapsed < item.Interval) { continue; } item.Elapsed -= item.Interval; if (item.Elapsed < 0 || item.Elapsed > 0.03f) { item.Elapsed = 0; } if (item.RepeatCount > 0) { item.RepeatCount--; if (item.RepeatCount == 0) { item.isDeleted = true; m_toRemove.Add(item); } } if (item.Callback != null) { try { item.Callback(item.Param); } catch (Exception e) { item.isDeleted = true; Debug.LogException(e); } } } // 移除废弃集合 foreach (TimerRepeatInfo item in m_toRemove) { if (item.isDeleted && item.Callback != null) { m_items.Remove(item.Callback); ReturnToPool(item); } } m_toRemove.Clear(); // 添加新的集合 foreach (KeyValuePair <TimerCallback, TimerRepeatInfo> item in m_toAdd) { m_items.Add(item.Key, item.Value); } m_toAdd.Clear(); }