using System; using UnityEngine; using UnityEngine.Events; public class Clock : MonoBehaviour { public bool stopped { get; private set; } public DateTime alarmTime { get; set; } UnityAction alarmCallBack; public void AddListener(UnityAction _action) { alarmCallBack += _action; } public void Stop() { stopped = true; GameObject.Destroy(this.gameObject); } private void Awake() { this.gameObject.hideFlags = HideFlags.HideInHierarchy; } private void LateUpdate() { if (System.DateTime.Now > alarmTime) { try { if (alarmCallBack != null) { alarmCallBack(); alarmCallBack = null; } } catch (System.Exception ex) { DebugEx.Log(ex); } finally { Stop(); } } } public static Clock Create(DateTime _alarmTime, UnityAction _action) { var carrier = new GameObject(); GameObject.DontDestroyOnLoad(carrier); var clock = carrier.AddComponent(); clock.alarmTime = _alarmTime; clock.AddListener(_action); return clock; } public static Clock Create(int _seconds, UnityAction _action) { var carrier = new GameObject(); GameObject.DontDestroyOnLoad(carrier); var clock = carrier.AddComponent(); clock.alarmTime = System.DateTime.Now + new TimeSpan(_seconds * TimeSpan.TicksPerSecond); clock.AddListener(_action); return clock; } }