| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- using UnityEngine;
- using UnityEngine.UI;
- using StarterAssets; // Required to access the ThirdPersonController
- public class PlayerStats : MonoBehaviour
- {
- [Header("Stamina Settings")]
- public float maxStamina = 100f;
- public float currentStamina;
- public float drainRate = 25f;
- public float regenRate = 15f;
- public Slider staminaSlider;
- [Header("Movement Settings (Overrides)")]
- public float walkSpeed = 6f; // Set to 6 to be faster than enemies
- public float sprintSpeed = 12f; // Fast escape speed
- public float jumpHeight = 3f; // Better navigation for scale 1.0
- private ThirdPersonController _controller;
- private StarterAssetsInputs _inputs;
- void Start()
- {
- currentStamina = maxStamina;
- // Find the components on the PlayerArmature
- _controller = GetComponent<ThirdPersonController>();
- _inputs = GetComponent<StarterAssetsInputs>();
- // Set the UI and initial controller values
- if (staminaSlider != null)
- {
- staminaSlider.maxValue = maxStamina;
- staminaSlider.value = currentStamina;
- }
- if (_controller != null)
- {
- _controller.MoveSpeed = walkSpeed;
- _controller.SprintSpeed = sprintSpeed;
- _controller.JumpHeight = jumpHeight;
- }
- }
- void Update()
- {
- // 1. Logic: Are we moving AND holding the sprint key?
- bool isMoving = _inputs.move != Vector2.zero;
- bool isSprinting = _inputs.sprint && isMoving;
- // 2. Handle Stamina Drain/Regen
- if (isSprinting && currentStamina > 0)
- {
- currentStamina -= drainRate * Time.deltaTime;
- // If we run out of breath
- if (currentStamina <= 0)
- {
- currentStamina = 0;
- ForceWalk(); // Force the controller to slow down
- }
- }
- else
- {
- if (currentStamina < maxStamina)
- currentStamina += regenRate * Time.deltaTime;
- // If not actively sprinting, ensure speed is walk speed
- if (!isSprinting)
- {
- _controller.MoveSpeed = walkSpeed;
- }
- }
- // 3. Keep stamina between 0 and 100
- currentStamina = Mathf.Clamp(currentStamina, 0, maxStamina);
- // 4. Update the visual UI
- if (staminaSlider != null)
- {
- staminaSlider.value = currentStamina;
- }
- }
- // Helper to stop the sprint even if the player is holding Shift
- private void ForceWalk()
- {
- _controller.MoveSpeed = walkSpeed;
- _inputs.sprint = false; // This "un-clicks" the sprint for the player
- }
- }
|