#How to wait for X seconds?

1 messages · Page 1 of 1 (latest)

thorny widget
#

I'm trying to figure out how to create code that will wait for ten seconds. My current code is below but something is causing a problem. I don't know if it is necessarily the loop but something in my function isn't working. My code is below.

using System.Collections;
using System.Collections.Generic;
using System.Timers;
using UnityEngine;

public float ImmunityTimer;

ImmunityTimer = 10;
while (ImmunityTimer > 0){
  ImmunityTimer -= Time.deltaTime;
}
``` Let me know if there is a problem with this. I did cut some other code out but if this part looks fine then I'll try to check the other code.
#

Lmk if there is an alternative

fast socket
#

loops run until they have completed which means this entire loop happens in a single frame.
if this is inside of Update then you just need an if statement, not a while loop. if this is in a coroutine then you need to yield inside the loop. if this is anywhere that isn't called every frame then you need to rethink your logic

thorny widget
fast socket
#

it's not that it doesn't work, it's the fact that this loop does not wait in any way, it just keeps subtracting the current value of deltaTime from your variable until the condition is met.

#

let's take this loop for example:

var counter = 0;
while(counter < 10)
{
  counter++;
}

how long do you think this loop will take?

thorny widget
#

1 Frame

#

Wait no 10 frames

fast socket
#

how would it be 10 frames? at what point inside of that loop does another frame occur?

thorny widget
fast socket
#

Correct, it is 1 frame because the entire method runs to completion as part of a single Update call in the frame.
The same thing is happening inside of your loop, because the entire method runs to completion in a single frame your loop is counting all the way down to 0 in that single frame.

thorny widget
fast socket
#

yes, like i said in the very first message if this code is not somewhere being evaluated every frame then it won't work at all. You could consider putting your timer related stuff (and whatever happens after the timer is complete) inside of a coroutine and just start the coroutine from the trigger message, or you could put that logic inside of Update and flip a bool in the trigger message to start evaluating it (making sure to fix it so that you use an if statement and not a while loop)

thorny widget
#

I'm a new dev so I don't really know how coroutines work. I can do some research

thorny widget
thorny widget