/* * About: * Simple Timer class * * Features: * 3 Timer setup types : Duration, Repeater, Interval * * How To Use: * 1. Create a timer using Timer.CreateNew() * e.g. var timer = Timer.CreateNew(gameObject); * * 2. Setup Timer using Setup(), SetupRepeater() or SetupInterval() * e.g. timer.Setup(1); * * 3. Use timer.TimerHit property to check and do something about it * e.g. if(timer.TimerHit) Shoot(); * * How It Works: * Uses Unity Engine Update Loop * * Notes: * No Start Delay */ using UnityEngine; namespace asim.unity.utils { public class ComponentTimer : MonoBehaviour { private bool autoContinueRun; private bool currentRunEnded; private int maxRuns; private float timerEnd; private float timerStart; /* Public Accessors */ public bool IsRuning { get; private set; } public bool TimerReady { get { return IsRuning && currentRunEnded; } } public bool TimerHit { get { var hit = IsRuning && currentRunEnded; if (IsRuning && !autoContinueRun && currentRunEnded) { Continue(); } return hit; } } public float CurrentTimer { get; private set; } public float TotalTime { get; private set; } public int TotalRuns { get; private set; } /* Private */ private void Reset() { CurrentTimer = timerStart; TotalTime = 0; TotalRuns = 0; currentRunEnded = false; } private void Update() { if (!IsRuning) return; if (TotalRuns >= maxRuns) { IsRuning = false; currentRunEnded = true; return; } if (currentRunEnded) { if (autoContinueRun) { Continue(); } else { return; } } CurrentTimer += Time.deltaTime; TotalTime += Time.deltaTime; if (CurrentTimer >= timerEnd) { currentRunEnded = true; } } private void Continue() { CurrentTimer = timerStart; TotalRuns++; currentRunEnded = false; } /* Public */ public static ComponentTimer CreateNew(GameObject gameObject = null) { if (gameObject == null) gameObject = new GameObject(nameof(ComponentTimer)); var timer = gameObject.AddComponent(); return timer; } /// /// Simple timer that counts down from a set duration. /// public void Setup(float duration) { timerStart = 0; timerEnd = duration; maxRuns = 1; autoContinueRun = false; } /// /// Timer that counts down and automatically repeats /// public void SetupRepeater(float duration, bool autoContinueRun = true, int maxRuns = int.MaxValue) { timerStart = 0; timerEnd = duration; this.maxRuns = maxRuns; this.autoContinueRun = autoContinueRun; } /// /// Setup a custom timer /// public void SetupInterval(float start, float end, bool autoContinueRun = true, int maxRuns = int.MaxValue) { timerStart = start; timerEnd = end; this.maxRuns = maxRuns; this.autoContinueRun = autoContinueRun; } public void StartTimer() { IsRuning = true; Reset(); } public void StopTimer() { IsRuning = false; } public void PauseUnpauseTimer() { IsRuning = !IsRuning; } } }