| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- using UnityEngine;
- using UnityEngine.UI;
- using StarterAssets;
- public class PlayerStats : MonoBehaviour
- {
- [Header("Health Settings")]
- public float maxHealth = 100f;
- public float currentHealth;
- public Image healthFillImage;
- [Header("Stamina Settings")]
- public float maxStamina = 100f;
- public float currentStamina;
- public float drainRate = 25f;
- public float regenRate = 15f;
- public Image staminaFillImage;
- [Header("Movement Overrides")]
- public float walkSpeed = 6f;
- public float sprintSpeed = 12f;
- public float jumpHeight = 3f;
- private ThirdPersonController _controller;
- private StarterAssetsInputs _inputs;
- void Start()
- {
- currentHealth = maxHealth;
- currentStamina = maxStamina;
- _controller = GetComponent<ThirdPersonController>();
- _inputs = GetComponent<StarterAssetsInputs>();
- if (_controller != null)
- {
- _controller.JumpHeight = jumpHeight;
- }
- }
- void Update()
- {
- HandleStamina();
- UpdateUI();
- }
- void HandleStamina()
- {
- bool isMoving = _inputs.move != Vector2.zero;
- // 1. If we are OUT of stamina, force the sprint input to FALSE
- if (currentStamina <= 0)
- {
- _inputs.sprint = false;
- }
- // 2. Check if we are currently sprinting (Must have stamina AND be holding shift)
- if (_inputs.sprint && isMoving && currentStamina > 0)
- {
- currentStamina -= drainRate * Time.deltaTime;
- // Ensure the controller speeds are set (in case they got changed)
- _controller.SprintSpeed = sprintSpeed;
- }
- else
- {
- // 3. Regen stamina if not sprinting
- if (currentStamina < maxStamina)
- {
- currentStamina += regenRate * Time.deltaTime;
- }
- // Safety: Ensure walk speed is correct
- _controller.MoveSpeed = walkSpeed;
- }
- // Keep stamina in bounds
- currentStamina = Mathf.Clamp(currentStamina, 0, maxStamina);
- }
- public void TakeDamage(float amount)
- {
- currentHealth -= amount;
- if (currentHealth <= 0)
- {
- currentHealth = 0;
- // Prevent multiple game over triggers
- if (GameManager.Instance != null) GameManager.Instance.GameOver(false);
- }
- }
- void UpdateUI()
- {
- if (healthFillImage != null) healthFillImage.fillAmount = currentHealth / maxHealth;
- if (staminaFillImage != null) staminaFillImage.fillAmount = currentStamina / maxStamina;
- }
- }
|