Pomodoro.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System;
  5. namespace JTSystems
  6. {
  7. public class Pomodoro : MonoBehaviour
  8. {
  9. public static Pomodoro instance;
  10. List<PomodoroStruct> pomodoros = new List<PomodoroStruct>();
  11. List<PomodoroStruct> pomodorosToRemove = new List<PomodoroStruct>();
  12. private void Awake()
  13. {
  14. if (instance == null)
  15. instance = this;
  16. else
  17. Destroy(gameObject);
  18. }
  19. void Update()
  20. {
  21. CheckAllTimers();
  22. }
  23. public IEnumerator StartNewTimer(float timer, Action onTimerComplete)
  24. {
  25. yield return new WaitForEndOfFrame();
  26. pomodoros.Add(new PomodoroStruct(Time.time + timer, onTimerComplete));
  27. }
  28. private void CheckAllTimers()
  29. {
  30. foreach (PomodoroStruct pomodoro in pomodoros)
  31. if (Time.time > pomodoro.GetTimer())
  32. {
  33. pomodoro.GetOnTimerCompleteAction()?.Invoke();
  34. pomodorosToRemove.Add(pomodoro);
  35. }
  36. RemoveElapsedTimers();
  37. }
  38. private void RemoveElapsedTimers()
  39. {
  40. for (int i = 0; i < pomodorosToRemove.Count; i++)
  41. pomodoros.Remove(pomodorosToRemove[i]);
  42. }
  43. public static void AddTimer(float timer, Action onTimerComplete)
  44. {
  45. instance.StartCoroutine(instance.StartNewTimer(timer, onTimerComplete));
  46. }
  47. }
  48. public struct PomodoroStruct
  49. {
  50. float timer;
  51. Action onTimerComplete;
  52. public PomodoroStruct(float timer, Action onTimerComplete)
  53. {
  54. this.timer = timer;
  55. this.onTimerComplete = onTimerComplete;
  56. }
  57. public float GetTimer()
  58. {
  59. return timer;
  60. }
  61. public Action GetOnTimerCompleteAction()
  62. {
  63. return onTimerComplete;
  64. }
  65. }
  66. }