Coroutines with Unity!

Anurag Chawla
3 min readApr 8, 2021

--

As of now , we have only instantiated enemies by creating Prefabs & copying those prefabs in hierarchy window and cloning it.

How can we able to instantiate stream of those enemies and generate after certain interval of time to time.

For this purpose we have to have a Spawn Mangerthat will instantiate enemies using some sequence of time events.

Unity provides Scripting API and using C# we can modeled those sequence of events what is called — Coroutineis a function that can suspend its execution (yield) until the given Yield Instruction finishes. This co-routine return an IEnumerator as below code snippet.

private IEnumerator WaitAndPrint(float waitTime)
{
yield return new WaitForSeconds(waitTime);
print("Coroutine ended: " + Time.time + " seconds");
}

Let’s create an empty GameObject SpawnManger in hierarchy window & attach SpawnManager c# script as shown below.

Spawn Manager GameObject with Script

Below code snippet shows SpawnManager c# script contains the reference of GameObject _enemyPrefab.

SpawnManager Script having _enemyPref as GameObject

SpawnManager Class contains private field _enemyPrefab that can be accessed in Inspector using SerializedField and assigned to Enemy, so that we can reference the enemies later in coroutine.

Added EnemyPrefab to the SpawnManager GameObject

Here below script shows the coroutine -SpawnRoutine that Instantiate _enemyPrefab from top of screen at y-axis =7.0f at random x-axis between -11.0f to 11.0f and with no rotation (Quanternion.identity) . This keep on instantiating every 5 sec using yield returns new WaitForSeconds(5.0f) under the while condition.

SpawnManager having Co-routine — SpawnRoutine that spawns GameObject every 5 seconds .

Note : To start CoRoutine — we have StartCoroutine Method() that takes a parameter -coroutine name or passing coroutine method.

When Coroutine starts — stream of enemies start instantiating after every 5 seconds and keep on clutter on the Game Scene even if Player gets died as shown below.

Clutter of Enemies — using Coroutine

In the next article — we see how clutter of enemies can be cleaned up or made constant as soon as Player get died.

@GameDevHQ-Day 11…

--

--

Anurag Chawla
Anurag Chawla

Written by Anurag Chawla

Emerging Technologies - Power Virtual Agents | AI Chatbots | Multi-Cloud & DevOps | UI Technologies - React , Angular | Gaming Technolgies - Unity, XR- AR/VR

No responses yet