- Home /
Troubles with making a do while loop work
I'm trying to make a function where a character keep going up as long as you press the jump button and that it hasn't been pressed for longer than 2 seconds.
But when i call this loop the condition automatically becomes the limit (so here the timer directly becomes 2 when i call the loop) and strangest of all it keeps working even though its while condition is now false (so i can just jump forever)
Here the part of the code where the jump is happening.
if (charactercontroller.isGrounded == true)
{
ySpeed = -0.9f;
jumping = false;
timer = 0f;
if(Input.GetKeyDown("space") == true)
{
jumping = true;
}
}
if (jumping == true)
{
do
{
if (Input.GetKey("space") == true)
{
ySpeed = jumpSpeed;
timer += Time.deltaTime;
}
else
{
jumping = false;
}
}
while (timer <= 2f);
Answer by Hellium · Mar 07 at 11:29 AM
Supposing your code is called in Update:
if (jumping == true)
{
if (Input.GetKey("space") && timer <= 2f)
{
ySpeed = jumpSpeed;
timer += Time.deltaTime;
}
else
{
jumping = false;
}
}
Thanks your version of doing it worked. Still wonder about the weird reaction of the do while loop. Guess some things will just remain as mysteries.
Your loop simply never gives back the control to Unity.
Unity won't magically pause your loop to update the frame.
Update is already running every frame, so just need to check whether you're pressing the key and if the timer hasn't elapsed this frame