Hi All,
I’m not sure if I’m misunderstanding C#, Unity, or both.
Within my Update() method I’m calling:
if (Input.GetKey(KeyCode.LeftShift) && StaminaBar.instance.currentStamina > 0f)
{
gameObject.GetComponent<CharacterController>().Move(transform.TransformDirection(input.normalized * speed * sprint * Time.deltaTime + yVelocity * Vector3.up * Time.deltaTime));
StaminaBar.instance.UseStatmina(0.1f);
}
else if (Input.GetKey(KeyCode.LeftShift) && StaminaBar.instance.currentStamina <= 0f)
{
gameObject.GetComponent<CharacterController>().Move(transform.TransformDirection(input.normalized * speed * Time.deltaTime + yVelocity * Vector3.up * Time.deltaTime));
}
The intention is that while you’re holding Shift and the character’s stamina is greater than 0, the character is sprinting (sprint variable), else if you’re holding shift and the character’s stamina is less than or equal to 0 then you’re back to normal speed. However, upon reaching the end of stamina bar (less than or equal to 0), the character is still able to sprint.
I know that initially the IF statement would never get to the “else if” portion, since starting off you would have stamina. However, since Update() is called once per frame, if I continued holding the Shift key until the stamina was less than or equal to 0, wouldn’t it eventually reach the “else if” portion?
I’ve tried using a bool switch as well, but I wasn’t getting that to work either. Stamina script is here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class StaminaBar : MonoBehaviour
{
public Slider staminaBar;
public float maxStamina = 100;
public float currentStamina;
public static StaminaBar instance;
private Coroutine regen;
private void Awake()
{
instance = this;
}
void Start()
{
currentStamina = maxStamina;
staminaBar.maxValue = maxStamina;
staminaBar.value = maxStamina;
}
public void UseStatmina(float amount)
{
if (currentStamina - amount > 0)
{
currentStamina -= amount;
staminaBar.value = currentStamina;
if (regen != null)
{
StopCoroutine(regen);
}
regen = StartCoroutine(RegenerateStamina());
}
else
{
Debug.Log("Not enough stamina.");
}
}
private IEnumerator RegenerateStamina()
{
yield return new WaitForSeconds(2);
while(currentStamina < maxStamina)
{
currentStamina += maxStamina / 100;
staminaBar.value = currentStamina;
yield return new WaitForSeconds(0.1f);
}
regen = null;
}
}
