- Home /
The question is answered, right answer was accepted
Stamina, Delay C# Script
I have huge problem with making Stamina Script in C# for my survival game. Idea is simple. Stamina = 100 (which is max stamina value) when player runs which is left shift button, Stamina goes down by 1. If player stops running, there is 5 seconds delay before stamina regenerates and then stamina goes up by 1 until it reaches 100. Sounds simple however I tried everything and in most cases when I start running (using stamina) while stamina was reacharging, everything breaks. Sometimes delay is ignored and it doesn't wait 5 seconds and keeps regenerating or it regenerates few numbers up and then stops for sec and goes up again. It's just huge mess. (As refference, I'm trying to make stamina like in game Unturned) Can anyone help me, how to do it?
public float Stamina = 100;
public float MaxStamina = 100f;
if (Input.GetKey(KeyCode.LeftShift))
{
Stamina = Stamina -= 1 * Time.deltaTime * 5;
}
Answer by Elarm00 · Jun 19, 2017 at 02:39 PM
Thats pretty easy, all you have to do is add some timer... ex.
//---------------------------------------------------------
public float Stamina = 100.0f;
public float MaxStamina = 100.0f;
//---------------------------------------------------------
private float StaminaRegenTimer = 0.0f;
//---------------------------------------------------------
private const float StaminaDecreasePerFrame = 1.0f;
private const float StaminaIncreasePerFrame = 5.0f;
private const float StaminaTimeToRegen = 3.0f;
//---------------------------------------------------------
private void Update()
{
bool isRunning = Input.GetKey(KeyCode.LeftShift);
if (isRunning)
{
Stamina = Mathf.Clamp(Stamina - (StaminaDecreasePerFrame * Time.deltaTime), 0.0f, MaxStamina);
StaminaRegenTimer = 0.0f;
}
else if (Stamina < MaxStamina)
{
if (StaminaRegenTimer >= StaminaTimeToRegen)
Stamina = Mathf.Clamp(Stamina + (StaminaIncreasePerFrame * Time.deltaTime), 0.0f, MaxStamina);
else
StaminaRegenTimer += Time.deltaTime;
}
}
Thank you so much! It took me 3 days to figure this out and you solved my problem in few $$anonymous$$utes! I also modified this script a bit by adding multipliers so it will drain sta$$anonymous$$a faster.
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Player prefab instantiation 1 Answer
I can't use Rigidbody2D in my scripts, I can't find rigidbody2d in my script 3 Answers
Multiple Cars not working 1 Answer