Whenever I press shift and let go, the stamina keeps on regenerating until it reaches 100. Or in some cases if I press shift and let go, it will regenerate ~10 stamina, and then stop and start over again.
Try this code
private void Sprinting()
{
if (Input.GetKeyDown(KeyCode.LeftShift) && !isSwimming && !isCrouching && currentStamina > 0)
{
isSprinting = true;
if (staminaRegen != null)
{
StopCoroutine(staminaRegen);
}
}
// Check for releasing the Left Shift key separately
if (Input.GetKeyUp(KeyCode.LeftShift) && !isSwimming)
{
isSprinting = false;
moveSpeed = moveSpeed2;
}
if (isSprinting)
{
moveSpeed = moveSpeed2 + sprintMultiplier;
currentStamina -= (staminaDrain * Time.deltaTime);
}
if (!isSprinting)
{
// Start stamina regeneration coroutine if not sprinting
if (staminaRegen == null)
{
staminaRegen = StartCoroutine(StaminaRegeneration());
}
}
UnityEngine.Debug.Log(isSprinting);
staminaBar.value = currentStamina;
}
// …
IEnumerator StaminaRegeneration()
{
yield return new WaitForSeconds(2);
if (currentStamina < maxStamina)
{
currentStamina += staminaRegenRate * Time.deltaTime;
staminaBar.value = currentStamina;
}
yield return regenTick;
staminaRegen = null;
}