Coroutines — set it and forget it

Just set the spawner and walk away!!

Now to add some challenge to our game. Let’s randomly spawn some more enemies.

The SpawnManager GameObject will control spawning objects for us.

To start with, we will pass it the Prefab that we want spawned as well as the container to put the spawned GameObjects in.

Now that the script has what we want and where to put it, lets talk about when to spawn.

Coroutines allow us to start a process that will happen after a certain amount of time.

In this case we are spawning an object, setting the parent container, and then waiting. We have a random value set on the spawn timer. This will allow for some mystery on when the next object will be spawned.

Starting the coroutine requires a special method call:

As mentioned earlier, we passed in a place to store newly Instantiated enemies. Keeping the spawned enemies under control is always a good idea to keep you hierarchy tidy if you ever need to debug other areas.

One of the best features of C# has to be the use of Properties. It allows you to setup your getter and setter methods through the property.

You can set whether to use default get and set if you don’t want an underlying variable. You can also just expose the value in the get and leave the set undefined so that it is inaccessible. However, in our case we wanted the Player class to update this variable with its status on player death.