Coroutines

I have an enemy script that uses a coroutine to dispatch enemies as needed. It works fine and the enemies are sent precisely on time. As the project got bigger I added more coroutines in different scripts doing different things. Now I notice sometimes some enemies are not being sent exactly on time. Im assuming coroutines affect each other in some way since they are all pausing the code?

Corourines just pause the method while continuing the functionality of the rest of the game code.
Coroutines do not interfere with eachother.

Use debug.log to see what happens when to see why this happens

1 Like

How far off are we talkin’ here?

Time is not usually continuous in the computer world. If your coroutine yields WaitForSeconds(10) or something, it’s never going to resume at exactly 10 seconds. It’s going to be scheduled on the next frame after 10 seconds elapses. At the typical frame rate of 60 frames per second, the timing could be as much as 0.016 seconds off. Even more if you have performance slow-downs. This should not be enough for anyone to notice unless you have a bunch of independently acting agents that are supposed to be in-sync.

If we’re talking about more than a second, then it’s probably a bug in your code or something.

Yes it’s a lot more than a second. I’ll have to recheck the code and see what’s happening.

Coroutines definitely do not do anything like “pause the code.” :slight_smile:

Check it:

Coroutines in a nutshell:

Splitting up larger tasks in coroutines:

Coroutines are NOT always an appropriate solution: know when to use them!

Our very own Bunny83 has also provided a Coroutine Crash Course:

https://answers.unity.com/questions/1749615/coroutines-ienumerator-not-working-as-expected.html?childToView=1749714#answer-1749714