PlayerStats.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using StarterAssets; // Required to access the ThirdPersonController
  4. public class PlayerStats : MonoBehaviour
  5. {
  6. [Header("Stamina Settings")]
  7. public float maxStamina = 100f;
  8. public float currentStamina;
  9. public float drainRate = 25f;
  10. public float regenRate = 15f;
  11. public Slider staminaSlider;
  12. [Header("Movement Settings (Overrides)")]
  13. public float walkSpeed = 6f; // Set to 6 to be faster than enemies
  14. public float sprintSpeed = 12f; // Fast escape speed
  15. public float jumpHeight = 3f; // Better navigation for scale 1.0
  16. private ThirdPersonController _controller;
  17. private StarterAssetsInputs _inputs;
  18. void Start()
  19. {
  20. currentStamina = maxStamina;
  21. // Find the components on the PlayerArmature
  22. _controller = GetComponent<ThirdPersonController>();
  23. _inputs = GetComponent<StarterAssetsInputs>();
  24. // Set the UI and initial controller values
  25. if (staminaSlider != null)
  26. {
  27. staminaSlider.maxValue = maxStamina;
  28. staminaSlider.value = currentStamina;
  29. }
  30. if (_controller != null)
  31. {
  32. _controller.MoveSpeed = walkSpeed;
  33. _controller.SprintSpeed = sprintSpeed;
  34. _controller.JumpHeight = jumpHeight;
  35. }
  36. }
  37. void Update()
  38. {
  39. // 1. Logic: Are we moving AND holding the sprint key?
  40. bool isMoving = _inputs.move != Vector2.zero;
  41. bool isSprinting = _inputs.sprint && isMoving;
  42. // 2. Handle Stamina Drain/Regen
  43. if (isSprinting && currentStamina > 0)
  44. {
  45. currentStamina -= drainRate * Time.deltaTime;
  46. // If we run out of breath
  47. if (currentStamina <= 0)
  48. {
  49. currentStamina = 0;
  50. ForceWalk(); // Force the controller to slow down
  51. }
  52. }
  53. else
  54. {
  55. if (currentStamina < maxStamina)
  56. currentStamina += regenRate * Time.deltaTime;
  57. // If not actively sprinting, ensure speed is walk speed
  58. if (!isSprinting)
  59. {
  60. _controller.MoveSpeed = walkSpeed;
  61. }
  62. }
  63. // 3. Keep stamina between 0 and 100
  64. currentStamina = Mathf.Clamp(currentStamina, 0, maxStamina);
  65. // 4. Update the visual UI
  66. if (staminaSlider != null)
  67. {
  68. staminaSlider.value = currentStamina;
  69. }
  70. }
  71. // Helper to stop the sprint even if the player is holding Shift
  72. private void ForceWalk()
  73. {
  74. _controller.MoveSpeed = walkSpeed;
  75. _inputs.sprint = false; // This "un-clicks" the sprint for the player
  76. }
  77. }