using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Stamina : Singleton { public int CurrentStamina { get; private set; } // The player's current stamina level [SerializeField] private Sprite fullStaminaImage, emptyStaminaImage; // Sprites representing full and empty stamina units [SerializeField] private int timeBetweenStaminaRefresh = 3; // Time interval for automatic stamina regeneration private Transform staminaContainer; // UI container holding stamina images private int startingStamina = 3; // Initial stamina value when the game starts private int maxStamina; // The maximum stamina value the player can have const string STAMINA_CONTAINER_TEXT = "Stamina Container"; // Name of the UI container holding stamina images // Initialize stamina values and set the starting stamina protected override void Awake() { base.Awake(); maxStamina = startingStamina; CurrentStamina = startingStamina; } // Find the stamina container in the UI on start private void Start() { staminaContainer = GameObject.Find(STAMINA_CONTAINER_TEXT).transform; } // Decrease stamina by 1 and update the stamina UI public void UseStamina() { CurrentStamina--; UpdateStaminaImages(); } // Increase stamina by 1 if it's below the max and update the stamina UI public void RefreshStamina() { if (CurrentStamina < maxStamina) { CurrentStamina++; } UpdateStaminaImages(); } // Continuously refresh stamina after a set interval private IEnumerator RefreshStaminaRoutine() { while (true) { yield return new WaitForSeconds(timeBetweenStaminaRefresh); RefreshStamina(); } } // Update the stamina UI based on the current stamina level private void UpdateStaminaImages() { for (int i = 0; i < maxStamina; i++) { if (i <= CurrentStamina - 1) { staminaContainer.GetChild(i).GetComponent().sprite = fullStaminaImage; // Show full stamina image } else { staminaContainer.GetChild(i).GetComponent().sprite = emptyStaminaImage; // Show empty stamina image } } // Start the stamina refresh routine if stamina isn't full if (CurrentStamina < maxStamina) { StopAllCoroutines(); StartCoroutine(RefreshStaminaRoutine()); } } }