A simple timer implementation in Unity
Place TimerManager.cs on a GameObject in your Scene and pass a callback function to timer.timeOut.AddListener()
A new Timer adds itself to TimerManager.Singleton, which updates all timers in a single Update call. A Stopped timer is removed from the manager.
To keep removal quick, instead of List.Remove, the index is nulled and added to a stack of free indices. The Add method checks for free slots before pushing to the List.
Not inheriting from MonoBehaviour means no OnDestroy or OnDisable method, so looping Timers have to be explicitly stopped by their callers or they'll run forever.
The API's simple:
- Start zeros the timer, and runs it if it's not already running
- Stop zeros and stops the timer if it's running or paused
- Pause stops the timer and marks it paused, but does not zero it
- Unpause starts the timer without zeroing it, but only if it's marked paused. Note that Start and Stop both unmark paused.
- Having both Start/Stop and Pause/Unpause lets you choose whether or not an object's timer is reset (for example, if it's disabled and later re-enabled).
- Progress returns a number between 0 and 1 representing what percentage of the timer has passed (useful for Lerps)
- IsRunning returns true if the timer is running, false otherwise
- Looping can be enabled by setting the Loop property to true