using System; using UnityEngine; using System.Collections.Generic; using UnityEngine.Events; public class Clock { public bool stopped { get; set; } DateTime alarmTime; UnityAction alarmCallBack; public Clock(DateTime alarmTime, UnityAction callBack) { this.alarmTime = alarmTime; this.alarmCallBack = callBack; } public bool CanAlarm() { return DateTime.Now >= alarmTime; } public void Execute() { if (alarmCallBack != null) { alarmCallBack(); alarmCallBack = null; } } static List clocks = new List(); public static void Init() { new LogicUpdate().Start(OnUpdate); } public static Clock AlarmAt(DateTime alarmTime, UnityAction callBack) { var clock = new Clock(alarmTime, callBack); clocks.Add(clock); return clock; } public static Clock AlarmAfter(double seconds, UnityAction callBack) { var clock = new Clock(DateTime.Now.AddSeconds(seconds), callBack); clocks.Add(clock); return clock; } public static void Stop(Clock clock) { if (clocks.Contains(clock)) { clock.stopped = true; } } static void OnUpdate() { for (var i = clocks.Count - 1; i >= 0; i--) { var clock = clocks[i]; if (clock.stopped) { clocks.RemoveAt(i); continue; } if (clock.CanAlarm()) { try { clock.Execute(); clocks.RemoveAt(i); } catch (Exception e) { Debug.LogException(e); } } } } }