https://www.youtube.com/watch?v=iawgn9pktPI&t=906s
using System;
using System.Collections.Generic;
using UnityEngine;
public class TimerManager : MonoBehaviour {
//Singleton pattern
private static TimerManager _instance = null;
private static readonly object _padlock = new object();
TimerManager() { }
public static TimerManager Instance {
get {
lock (_padlock) {
if (_instance == null) {
var obj = new GameObject("TimerManager", typeof(TimerManager));
_instance = obj.GetComponent<TimerManager>();
}
return _instance;
}
}
}
public List<Timer> _timers = new List<Timer>();
/// <summary>
///
/// Example: TimerManager.active.AddTimer(2, ()=> {print(Time.time);} , true);
/// </summary>
/// <param name="delay"></param>
/// <param name="action"></param>
/// <param name="looping"></param>
public void AddTimer(float delay, System.Action action, bool looping = false) {
_timers.Add(new Timer(delay, action, looping));
}
private void Update() {
for (int i = 0; i < _timers.Count; i++) {
if(_timers[i]._executionTime < Time.time)
_timers[i]._action?.Invoke();
if (!_timers[i]._looping) {
_timers.RemoveAt(i);
}
}
}
}
public class Timer {
public float _executionTime;
public bool _looping;
public System.Action _action;
private float _delay;
public Timer(float delay, System.Action action, bool looping = false) {
_executionTime = Time.time + delay;
_action = action;
_looping = looping;
_delay = delay;
if (looping)
action += () => { _executionTime = Time.time + delay; };
}
}