Road TO Dev — Coroutines lets you control that spawn.
Ok so what is a Coroutine? Well it’s a function that allows you to create pauses in your lines of code or if you’d like to continuously do “something” like spawning enemy waves for example. With that said let’s take a look at setting it up.
Well first we need to set up an object to actually be our spawner. This is easy all you need to do is create an empty game object in the scene. Now if you want to actually spawn objects directly from this you can, but you need to remember to position it where you want them to start spawning, otherwise through code magic we can just tell the objects where to spawn on screen and the location of the spawn manager won’t really matter. For what I am doing I’ll just zero it.
Ok now we need to setup our code. First of course create a SpawnManager script and then let’s add the important bits. You’ll want to make sure to prefab your enemy if you haven’t already. Once that’s done setup the spawn manager to reference that game object.
Now we need to figure out where to start spawning our object and within what boundaries. That’s easy enough just move your enemy on your scene to the edges of your screen. Keep in mind once you have one position on the x the negative/positive variant should be your other side same for your y.
As you can see it’s roughly 9.5 on the x and 7.5 on the Y so we know -9.5 is the other side of that screen. We don’t need the other Y because our enemy wraps back up to the top already. So we can setup our code to get our spawn position and lets randomize that x so it doesn’t always spawn in the same spot.
Now the Instantiate!
Don’t forget to drag and drop the enemy prefab from the prefabs folder into the game manager don’t use the enemy already in the scene. You can delete the enemy from the scene now too. Now this is where you get what you see in the thumbnail. To avoid that we need to setup our Coroutine.
We need to tell our spawn manager to only spawn these enemies every so often… let’s say 5 seconds. We will create a method for spawningEnemies to help keep our code tidy and then we need to make our IENumerator. This will include a While Loop which make sure you understand these before trying to use them as they will freeze/crash unity if not put in check. We add the waitforseconds to help with that. Also given we are controlling the time we need to call this only once from the start and not in update.
And now you have it here’s our spawner working as intended!