PlayerStats.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. public class PlayerStats : MonoBehaviour
  4. {
  5. public float maxStamina = 100f;
  6. public float currentStamina;
  7. public float drainRate = 25f; // Increased for testing
  8. public float regenRate = 15f;
  9. public Slider staminaSlider;
  10. private CharacterController _characterController;
  11. void Start()
  12. {
  13. currentStamina = maxStamina;
  14. _characterController = GetComponent<CharacterController>();
  15. // Set the slider's max value to match our code automatically
  16. if (staminaSlider != null)
  17. {
  18. staminaSlider.maxValue = maxStamina;
  19. staminaSlider.value = currentStamina;
  20. }
  21. }
  22. void Update()
  23. {
  24. // 1. Get the actual horizontal movement speed
  25. Vector3 horizontalVelocity = new Vector3(_characterController.velocity.x, 0, _characterController.velocity.z);
  26. float currentSpeed = horizontalVelocity.magnitude;
  27. // 2. Check if we are moving faster than a basic walk
  28. // In Starter Assets, Walk is usually 2.0 and Run is 6.0.
  29. // We check for > 3.0 to be safe.
  30. if (currentSpeed > 3.0f)
  31. {
  32. currentStamina -= drainRate * Time.deltaTime;
  33. }
  34. else
  35. {
  36. currentStamina += regenRate * Time.deltaTime;
  37. }
  38. Debug.Log("Current Speed: " + currentSpeed);
  39. // 3. Keep stamina between 0 and 100
  40. currentStamina = Mathf.Clamp(currentStamina, 0, maxStamina);
  41. // 4. Update the visual UI
  42. if (staminaSlider != null)
  43. {
  44. staminaSlider.value = currentStamina;
  45. }
  46. }
  47. }