using System; using UnityEngine; namespace asim.unity.utils { /// /// Handels running of action after a delay or repeat. Executes via a static extension class /// Uses ComponentTimer /// internal class TimerAction : MonoBehaviour { Action action; ComponentTimer timer; internal static void CreateDelayedAction(Action action, float delay) { var go = new GameObject(); var timerAction = go.AddComponent(); go.hideFlags = HideFlags.HideAndDontSave; timerAction.action = action; timerAction.timer = ComponentTimer.CreateNew(go); timerAction.timer.Setup(delay); timerAction.timer.StartTimer(); } internal static void CreateRepeatAction(Action action, float interval, int maxRuns = int.MaxValue) { var go = new GameObject(); var timerAction = go.AddComponent(); go.hideFlags = HideFlags.HideAndDontSave; timerAction.action = action; timerAction.timer = ComponentTimer.CreateNew(go); timerAction.timer.SetupInterval(0, interval, true, maxRuns); timerAction.timer.StartTimer(); } void Update() { if (timer.TimerHit) { action.Invoke(); } if (!timer.IsRuning) { Destroy(gameObject); } } } public static class TimerActionExtensions { public static void RunAfterDelay(this Action action, float delay) { TimerAction.CreateDelayedAction(action, delay); } public static void RunRepeat(this Action action, float interval, int maxRuns = int.MaxValue) { TimerAction.CreateRepeatAction(action, interval, maxRuns); } } }