Coroutines in Unity
Objective: Deactivate our TripleShot Power Up after X seconds using a timer a.k.a. Coroutine.
Here we have a videogame where we collect a Power Up and deactivate it after 5 seconds. How was it done? Let’s get into it.
In this article we are not going to dive into the implementation of other features, but if you want to check the Instantiation method, click HERE
When we collect the Power Up, a method is called into the player script by the OnTriggerEnter2D Unity event in our Power Up script that activates the TripleShot and starts the StopsTripleShot Coroutine.
Now we need a timer or a Coroutine to deactivate the TripleShot after 5 seconds.
For this, we are going to create a function that returns a WaitForSeconds object with a float value in seconds that will stop after certain time, in this case after disabling our _isTripleShotEnabled bool that controls our shooting.
With this logic, our player will be shooting the TripleShot projectile for 5 seconds and then, disabling it to shoot again the basic laser projectile.
It’s an easy and performant implementation that allows us to decide when to stop instantiating our PowerUp!
Imagine that for some reason we would want to reactivate our TripleShot, we could do it by adding another yield return new WaitForSeconds(seconds);
With this secuence of timers we can set any kind of delayed behaviours that will make our life easier thanks to the Coroutines.
BONUS
What if we wanted to spawn some enemies infinitely until we finish the level, load scene, etc…?
We could swap true with a bool variable and make some magic but that’s up to you!
Remember: You always need to start your Coroutine with StartCoroutine(EnemySpawner()); in this case.
Notes: You can stop a Coroutine with StopCoroutine(). A coroutine also stops when the GameObject it is attached to is disabled with SetActive(false).
You can stop all Coroutines running in the current MonoBehaviour with StopAllCoroutines().