How to use Coroutines?
This time we see how coroutines work. We use it to spawn a powerup on random x value and random time
This is a subject that can be dangerous sometimes.
In the last hour or so, I managed just to crash Unity with this, multiple times before I realized why that happened... :D
Coroutines are used to do something, run the code and wait for amount of seconds and run the code again.
You can start and end coroutines with these (You can also use StopAllCoroutines(); to stop all coroutines you have)
I used this in the 2D Space Shooter game and I will show you how I spawned a Powerup in random X and random time between 3–7sec.
We need an IEnumerator for this and a while loop so we can end the loop when we want just by changing from let’s say false to true and the loop ends. :)
We need a boolean which specifies if we can spawn powerup or not
Then we create a private GameObject for our powerup
This is what we use to make it happen. Let’s go down and understand what does what.
- We give the IEnumerator a name (SpawnPowerUp)
- Then we create a while loop, when _stopSpawning is false, we can do the code inside the while loop.
- We create a new Vector3 for our spawn, random on the X-axis -8f, 8f.
- After that we Instantiate(our powerup prefab, position where we want it, rotation of the game object)
- At the end of our while loop, we use yield return to wait for the second amount we want and then we start to run the code from the beginning again till our _stopSpawning is true
- With Random.Range we can specify that the time we wait is random between 3–7
We add this script in our Empty GameObject (Remember to reset the transform to 0,0,0) then name the Empty GameObject SpawnManager
Then we just add our Powerup prefab and we are done! :)
When you want to use this code for example in Start function you write
With this, we can’t crash unity! :)
Thank you for reading this far! Much love, and see you in the next one :)