Spawn Manager with Coroutine in Unity!


  • Coroutine is very useful when whenever we need to pause/perform a series of steps in sequence before any further action takes a place.

IEnumerator — the best friend of Coroutine

While Loop

Actual Code

  1. Create a new empty game object called ‘SpawnManager’
  2. Create a new script called ‘SpawnManager’ and add it to the game object that we just created above.
  3. In the script, create a new game object variable to get enemy prefab.
  4. Under void Start(), write ‘StartCoroutine(SpawnEnemies());
  5. As a new method, write ‘IEnumerator SpawnEnemies()’ that will execute when Coroutine starts.
  6. To create an infinite loop, write ‘While (true)’. Then, create lines of code to instantiate enemy prefab that will spawn at a random X position from the top of the game screen.
  7. Add ‘yield return new WaitForSeconds(3f)’ to pause for 3 seconds before resume again.

Tidy Up Spawned Enemies

  1. Create an empty game object under SpawnManager.
  2. Create a variable to link this EnemyContainer game object.
  3. Create a variable ‘newEnemy’ that will store the enemies that were instantiated.
  4. Write a line of code that will transfer the enemies to EnemyContainer.

Stop Spawning when the player dies

  • We can create a bool variable that will check whether the player is dead or alive and pass this onto the while loop condition.
  • We would also need to create a method that will be called out when the player is dead and let the while loop know & stop spawning the enemies.
  1. First, find GameObject that is called “SpawnManager”.
  2. Then, get a component called <SpawnManager>.
When the player is destroyed, the enemy is no longer spawned.




XR Unity Developer / Designer / Architect

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Azure Kubernetes Service (AKS)

Bulk Insert; Auto Increment; Hibernate; YES it’s possible

How loosely coupled independent teams can accelerate Product Development

Light and Dark Theme in Flutter

What do YOU want from SD-WAN? — Bits in Flight



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Du Young Yoon

Du Young Yoon

XR Unity Developer / Designer / Architect

More from Medium

Managers, Main Menu and Loading screen

Adding proximity detection so enemies can ram player

NgRx vs Observable Services: Stately Matters

top down view of a person’s shoes pointing forward with two arrows pointing to different paths to take

Writing parameterized unit tests in C# — Run the same test with various inputs