Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Scripts / Extensions / Timer.cs
  1. using System;
  2. namespace MyCollections.Timer
  3. {
  4. public abstract class Timer
  5. {
  6. protected float initialTime;
  7. public float Time { get; set; }
  8. public bool IsRunning { get; protected set; }
  9. public float Progress => Time / initialTime;
  10. public Action OnTimerStart = delegate { };
  11. public Action OnTimerStop = delegate { };
  12. protected Timer(float value)
  13. {
  14. initialTime = value;
  15. IsRunning = false;
  16. }
  17. public void Start()
  18. {
  19. Time = initialTime;
  20. if (!IsRunning)
  21. {
  22. IsRunning = true;
  23. OnTimerStart.Invoke();
  24. }
  25. }
  26. public void Stop()
  27. {
  28. if (IsRunning)
  29. {
  30. IsRunning = false;
  31. OnTimerStop.Invoke();
  32. }
  33. }
  34. public void Resume() => IsRunning = true;
  35. public void Pause() => IsRunning = false;
  36. public abstract void Tick(float deltaTime);
  37. }
  38. public class CountdownTimer : Timer
  39. {
  40. public CountdownTimer(float value) : base(value) { }
  41. public override void Tick(float deltaTime)
  42. {
  43. if (IsRunning && Time > 0)
  44. {
  45. Time -= deltaTime;
  46. }
  47. if (IsRunning && Time <= 0)
  48. {
  49. Stop();
  50. }
  51. }
  52. public bool IsFinished => Time <= 0;
  53. public void Reset() => Time = initialTime;
  54. public void Reset(float newTime)
  55. {
  56. initialTime = newTime;
  57. Reset();
  58. }
  59. }
  60. public class StopwatchTimer : Timer
  61. {
  62. public StopwatchTimer() : base(0) { }
  63. public override void Tick(float deltaTime)
  64. {
  65. if (IsRunning)
  66. {
  67. Time += deltaTime;
  68. }
  69. }
  70. public void Reset() => Time = 0;
  71. public float GetTime() => Time;
  72. }
  73. }