If you think that this tutorial may be of help to other, non-English speaking users, feel free to translate the text version below into other languages and distribute it (on Forums, blogs, social networks, emails, etc ...) .

The 3D model used in this tutorial:

es es Introducción a Coroutines y la función "yieldWaitForSeconds" en Unity

fr fr Introduction aux Coroutines et à la fonction "yield WaitForSeconds" dans Unity

de de Einführung in Coroutines und die Funktion"yield WaitForSeconds" in Unity

pt br Introdução a Coroutines e à função "yieldWaitForSeconds" no Unity

ru ru Введение в сопрограммы (Coroutines) и функцию "yield WaitForSeconds" в Unity

zh cn 协程和Unity中的“yield WaitForSeconds”Coroutines介绍

ja jp Unity の Coroutinesと"yieldWaitForSeconds"関数の概要

hi in परि चय Coroutines और "yield WaitForSeconds"समा रो ह में में Unit


In this tutorial:


Hello everyone!

This is an introductory tutorial on the use of Coroutines in Unity; that is: on the functions that can be performed concurrently with the main game execution cycle; I will deal with the topic with a practical example, which will make the concept clear and, in the meantime, I will take advantage of this to also use the WaitForSeconds function, which makes it wait for the execution of an operation for some seconds.

The tutorial is for those who already have a basic knowledge of C# programming in Unity; it has been recorded with the 2020 version of Unity; however, the Coroutines (which are available in many programming languages) are also available in previous versions of Unity and, of course, they will also be available in later versions.

In the scene that I am using in this example there is a 3D model of a naval gun.

Unity tutorial - Introduction to Coroutines 1

FIRING EVERY 3 SECONDS: THE AUTOSHOOT SCRIPT

We want to have the cannon fire the Prefab of a cannonball (a simple black sphere, actually) automatically every 3 seconds, until an external event occurs that interrupts this routine (in this scenario, the external intervention will be the user pressing the S key ("Stop")).

First of all, I create a script for the cannon, calling it "autoshoot".

Inside the main class, I define three variables:

  • public GameObject spawnPrefab

I will link the cannonball prefab to this public variable in the Unity Editor

  • Vector3 spawnPosition
  • Quaternion spawnRotation

I need the last variables to specify the starting point of the ball with respect to the cannon; I calculated this point and the initial orientation, so I initialize these two values within the Start function:

spawnPosition = transform.position + new Vector3(-1.2f, 1.8f, 0f)

spawnRotation = Quaternion.Euler(-10f, -90f, 0f)

Unity tutorial - Introduction to Coroutines 2

"PLEASE WAIT": THE YIELD WAITFORSECONDS FUNCTION

From the description of the problem it is clear that we have to implement a loop that repeats itself indefinitely (unless an external event blocks it) and that it must include a delay instruction, in order to make it wait 3 seconds before moving on to next iteration.

The instruction that allows us to wait for a few seconds is WaitForSeconds, which takes as its argument the number of seconds to wait.

At this point it is clear that the main loop to execute is given by this WHILE block (which I'm writing, for the moment, in an empty place in the script):

while(true) {

GameObject cannonBall = Instantiate(spawnPrefab, spawnPosition, spawnRotation, null);

yield return new WaitForSeconds(3);

}

Unity tutorial - Introduction to Coroutines 3

SELF-DESTRUCTION: DESTROY GAME OBJECT

The cannonball prefab comes with a script which, upon startup, provides an initial forward push to the ball and sets the object to self-destruct after 3 seconds, so as not to fill the virtual universe and the memory with cannonballs.

Unity tutorial - Introduction to Coroutines 4

THE IENUMERATOR SHOOT FUNCTION

Where should we place this WHILE block?

We cannot put it in Start, either due to a compilation error (we cannot put yield WaitForSeconds there), or because the program would actually be stuck in Start (DO NOT try to put it in Start without the WaitForSeconds, to try the While loop so defined: Unity would freeze); likewise, we cannot put it in Update...

The problem is not solved if we put WaitForSeconds in Update, without the while loop, because Update is still called on every frame of the game: WaitForSeconds would not delay it.

We must therefore insert this block of code inside a function that, in particular, returns the IEnumerator  type; we call this function shoot.

Unity tutorial - Introduction to Coroutines 5

STARTCOROUTINE

To start this function inside a Coroutine, we need to use the StartCoroutine instruction, which must have the function name as a parameter, between double quotes; since the cannon must start firing immediately, we write:

StartCoroutine("shoot");

within Start, immediately after the initialization of spawnPosition and spawnRotation.

Unity tutorial - Introduction to Coroutines 6

Let's save the script, go to the Unity editor and try the script defined up to this point.

Unity tutorial - Introduction to Coroutines 7

STOPPING AND RESTARTING THE COROUTINE

Let's go back to the script to insert two statements, so we can stop (S key) or restart (R key) the Coroutine:

if(Input.GetKeyDown(KeyCode.S)) StopCoroutine("shoot");

if(Input.GetKeyDown(KeyCode.R)) StartCoroutine("shoot");

Unity tutorial - Introduction to Coroutines 8

Let's save the script, go to the Unity editor and try the script defined up to this point.

Well, that's all for this short tutorial! I hope it was useful to you! See you soon!