Wish you could just freeze time and take a breather, or make something gradually fade away? Now you can with the power of Coroutines. In Unity all methods complete their work within a single frame but that really limits the kinds of things you can do. If you want to make something turn gradually invisible or for an enemy to take damage over time that only becomes possible with Coroutines. So how do you use coroutines? Let’s take a look below at an example.
Here it is in action. The text will pop up after 5 seconds.
Now you can see how a coroutine allows for all sorts of interesting behavior instead of allowing a method to execute instantly you can delay the method until a condition like a timer is met then execute. You could have an enemy die and then explode after a short timer for example. Let’s make a quick example of turning a cube invisible over 5 seconds and then when we hit a key to make it reappear, this is what it should look like.
So how do you do that? Let’s take a look at the script below. Just an important note, make sure that you have a material with a transparent shader otherwise there’s nothing to make transparent.
This looks like a lot but really it’s quite simple. Basically when we start the game, the Invisible() coroutine starts and then lerps between the current color and the desired color (transparent in this case) over about 5 seconds. When it’s fully transparent, if we hit the I key then it will turn opaque in the same way just reversed. We have the coroutineIsRunning bool to make sure the change goes uninterrupted.
Hopefully this really gets those creative juices flowing and lets you take some of ideas into reality. The versatility of coroutines cannot be overstated. Until next time, happy coding.