PauseableSimulationTimer.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using UnityEngine;
  2. namespace StinkySteak.SimulationTimer
  3. {
  4. public struct PauseableSimulationTimer
  5. {
  6. public static PauseableSimulationTimer None => default;
  7. private float _targetTime;
  8. private bool _isPaused;
  9. private float _pauseAtTime;
  10. public float TargetTime => GetTargetTime();
  11. public bool IsPaused => _isPaused;
  12. private float GetTargetTime()
  13. {
  14. if (!_isPaused)
  15. {
  16. return _targetTime;
  17. }
  18. return _targetTime + Time.time - _pauseAtTime;
  19. }
  20. public static PauseableSimulationTimer CreateFromSeconds(float duration)
  21. {
  22. return new PauseableSimulationTimer()
  23. {
  24. _targetTime = duration + Time.time
  25. };
  26. }
  27. public void Pause()
  28. {
  29. if (_isPaused) return;
  30. _isPaused = true;
  31. _pauseAtTime = Time.time;
  32. }
  33. public void Resume()
  34. {
  35. if (!_isPaused) return;
  36. _targetTime = GetTargetTime();
  37. _isPaused = false;
  38. _pauseAtTime = 0;
  39. }
  40. public bool IsRunning => _targetTime > 0;
  41. public bool IsExpired()
  42. => Time.time >= TargetTime && IsRunning;
  43. public bool IsExpiredOrNotRunning()
  44. => Time.time >= TargetTime;
  45. public float RemainingSeconds
  46. => Mathf.Max(TargetTime - Time.time, 0);
  47. }
  48. }