TimeManager.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using UnityEngine;
  2. using UnityEngine.InputSystem;
  3. using System;
  4. public class TimeManager : MonoBehaviour
  5. {
  6. [Header("Time Settings")]
  7. [SerializeField] private float[] speedMultipliers = { 1f, 2f, 10f };
  8. [SerializeField] private int currentSpeedIndex = 0;
  9. [SerializeField] private bool isPaused = false;
  10. public static event Action<float> OnTimeSpeedChanged;
  11. public static event Action<bool> OnPauseStateChanged;
  12. public float CurrentTimeScale => isPaused ? 0f : speedMultipliers[currentSpeedIndex];
  13. public bool IsPaused => isPaused;
  14. public int CurrentSpeedIndex => currentSpeedIndex;
  15. void Start()
  16. {
  17. ApplyTimeScale();
  18. }
  19. void Update()
  20. {
  21. // Handle speed control inputs
  22. var keyboard = UnityEngine.InputSystem.Keyboard.current;
  23. if (keyboard.digit1Key.wasPressedThisFrame)
  24. {
  25. SetSpeed(0);
  26. }
  27. else if (keyboard.digit2Key.wasPressedThisFrame)
  28. {
  29. SetSpeed(1);
  30. }
  31. else if (keyboard.digit3Key.wasPressedThisFrame)
  32. {
  33. SetSpeed(2);
  34. }
  35. else if (keyboard.tabKey.wasPressedThisFrame)
  36. {
  37. CycleSpeed();
  38. }
  39. }
  40. public void SetSpeed(int speedIndex)
  41. {
  42. if (speedIndex >= 0 && speedIndex < speedMultipliers.Length)
  43. {
  44. currentSpeedIndex = speedIndex;
  45. ApplyTimeScale();
  46. OnTimeSpeedChanged?.Invoke(CurrentTimeScale);
  47. Debug.Log($"Game speed set to {speedMultipliers[currentSpeedIndex]}x");
  48. }
  49. }
  50. public void CycleSpeed()
  51. {
  52. currentSpeedIndex = (currentSpeedIndex + 1) % speedMultipliers.Length;
  53. ApplyTimeScale();
  54. OnTimeSpeedChanged?.Invoke(CurrentTimeScale);
  55. Debug.Log($"Game speed cycled to {speedMultipliers[currentSpeedIndex]}x");
  56. }
  57. public void SetPaused(bool paused)
  58. {
  59. isPaused = paused;
  60. ApplyTimeScale();
  61. OnPauseStateChanged?.Invoke(isPaused);
  62. Debug.Log($"Game {(isPaused ? "paused" : "unpaused")}");
  63. }
  64. public void TogglePause()
  65. {
  66. SetPaused(!isPaused);
  67. }
  68. private void ApplyTimeScale()
  69. {
  70. Time.timeScale = CurrentTimeScale;
  71. }
  72. public float GetSpeedMultiplier()
  73. {
  74. return speedMultipliers[currentSpeedIndex];
  75. }
  76. public string GetSpeedText()
  77. {
  78. if (isPaused)
  79. return "Paused";
  80. return $"{speedMultipliers[currentSpeedIndex]}x";
  81. }
  82. }