I’m trying to setup a sprinting/ stamina system. Right now when I stop sprinting it calls a coroutine to wait a few seconds and then start replenishing. I’ll admit I’m no expert on coroutines, but when I stop sprinting I want the replen to start (with delay), and if I start sprinting again stop the replen to be retriggered after not sprinting again but the StopCoroutine doesn’t seem to work like I want.
Code Below:
public class PlayerControl : MonoBehaviour
{
[SerializeField] float maxStamina = 10f;
[SerializeField] float currentStamina = 0f;
[SerializeField] float burnRate = 2f;
[SerializeField] float staminaReplenDelay = 2f;
[SerializeField] float staminaReplenRate = 0.05f;
void Update()
{
if (currentStamina > maxStamina)
{
currentStamina = maxStamina;
}
if (!isSprinting && currentStamina < maxStamina)
{
StartCoroutine(ReplenStamina());
}
if (isSprinting)
{
playerSpeed = sprintSpeed;
currentStamina -= (burnRate * Time.deltaTime);
if (currentStamina < 0)
{
isSprinting = false;
}
}
}
IEnumerator ReplenStamina()
{
yield return new WaitForSeconds(staminaReplenDelay);
while (currentStamina < maxStamina)
{
if (isSprinting) { yield break; }
currentStamina += staminaReplenRate * Time.deltaTime ;
if (currentStamina >= maxStamina)
{
currentStamina = maxStamina;
}
yield return new WaitForSeconds(.02f);
}
}
void OnSprint()
{
if (currentStamina > 0)
{
isSprinting = !isSprinting;
StopCoroutine(ReplenStamina());
}
}
}
Any pointers would be greatly appreciated, Thanks.