I’m working on a game where I need to instantiate cars after a certain time delay. I decided to use coroutines to do this, but I don’t fully understand how they work yet. Just for a test, I made the following coroutine:
IEnumerator SayHi() {
print("hi");
yield return new WaitForSeconds(2f);
}
and I ran it in the Update() method:
void Update()
{
StartCoroutine(SayHi());
}
The problem is that, according to the console, the coroutine ignores the WaitForSeconds() call and just spams hi instead of writing it in two-second intervals.
I think you’re confused about a how coroutines work. The code is behaving exactly as you have written it. First off, you need to understand exactly what your coroutine is doing:
It prints “hi”. This happens immediately every time you start the coroutine because it’s the first line in the coroutine.
It waits for two seconds
There is no 3, the coroutine ends after waiting two seconds. There was no point in waiting two seconds because you don’t have anything that happens after the wait.
Now, you are starting this coroutine every single frame (you put StartCoroutine in Update). So here’s what’s going to happen, every single frame:
It will print “hi”
It will start the process of pointlessly waiting for two seconds.
Nowhere in here is anything that would cause a two second wait between the times it prints “hi”. Nothing about this coroutine or any coroutine will cause Update not to run every single frame. That’s what Update does, it runs every frame. Coroutines cannot cause delays in other code, only in themselves.