Can someone explain coroutine?

Hi forums,

I am trying to make a game that switches between a red and green background and you have to press space when its green. It is sort of a timing/reaction time game. I use SetActive(); to show and hide the red and green backgrounds. The only problem is that when I set the a gameObject to false it doesn’t run the Update functions. I have heard of using a coroutine as a solution but I don’t really understand it. Can someone explain this to me or help me come up with another solution? Thank you in advance.


normal functions dont let the rest of the code run until they are finished

coroutines have a functionality to pause temporarily and let the rest of the code run, and come back from that pause where they left off last.

coroutines are ideal if you want to do an effect overtime

as for your problem you should disable only the renderer and not the whole gameobject

@Game_Krator

Use code tags when posting code.

Also, this question belongs to scripting forum (= don’t expect too many answers here…)

Coroutines get called each frame update.

So like Unity calls your Update() method each frame, it will also update coroutines that are running/started from that specific MonoBehaviour script.

So you could have a for loop or while loop in your Coroutine, and when you put a yield there, coroutine will each update run your code to that line, and then it bails out until next frame update (if there is something to be executed after your yield statement, or your yield is in a loop that isn’t done yet).

You can find quite good explanation in the documentation:

And if that isn’t enough, if you simply google, you’ll find several tutorials and articles about Unity Coroutines.

Sooner using of two backgrounds is redundant.
Simpler use the SpriteRenderer of the object and change its color.
Unity - Scripting API: SpriteRenderer.color (unity3d.com)
SpriteRenderer comonent could be added in inspector.