Spawn Manager with Coroutine in Unity!

Coroutine

  • 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

How to Add Columns to Pandas at a Specific Location

Starting the server

145. Binary Tree Postorder Traversal

Array iteration performance in C# —  ArraySegment<T>

OpenJPA + Oracle Identity Column

INTRO TO C++: Controlling the Flow of a Program — Using For Loop, While Loops, Do-While and Switch…

Deploy Postgres in Horizontally Scalable Architecture using Kubernetes, Docker, and Kafka on IBM…

Property-based testing #4: Unifying Random Generation and Shrinking

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

Using C# Switch Statements

Tips to Improve Unity Performance

The Decorator Pattern in Unity

Coroutines in Unity