I have a timer script that isn’t working whats wrong?
void Update()
{
if (SprintRecharge <= 9)
{
if (Input.GetKey(KeyCode.LeftShift))
{
SprintRecharge -= 1f;
}
else
{
SprintRecharge += 1f;
}
}
}
You should never increase a timer, only decrease. Otherwise once you increase it beyond 9 your If statement will never be true again unless you’re setting SprintRecharge elsewhere in your code. Also, you should multiply your countdown with Time.deltaTime otherwise it’ll be faster/slower than you expect depending on framerate.
void Update()
{
if (timer > 0f)
{
timer -= 1f * Time.deltaTime;
}
}
Now, you can set timer anywhere in the class (I guess once your character is out of stamina - going with the example you’ve provided). Setting it to timer = 10f for example will cause a countdown of 10 seconds. When setting a timer use a CONSTANT field with a descriptive name so it’s clear and easy to change in the future.
I don’t know what you’re expecting to happen, but assuming that your sprint recharge starts at 0
, that variable will count up to 9
within 9 frames, which is 150 milliseconds if the game is running at 60 fps. After reaching 9
, the entire code within that first if statement’s body stops running, as SprintRecharge
is not <= 9
anymore.
You should change the order of your if statements. You probably want to make the input check the outer statement.
In addition, use Time.deltaTime
so your sprint meter doesn’t fill up twice as fast if the game is running on twice the framerate.
Ok thank you I will definitely use this!