Coroutines
Generally a function will run from start to finish.Sometimes there is need to delay or pause the execution of some scripts and to run timed events .This type of timed functions are called Coroutines.
“It is essentially a function declared with a return type of IEnumerator and with the yield return statement included somewhere in the body. The yield return line is the point at which execution will pause and be resumed the following frame”.
Here, Yield is like return type statement where execution gets stopped and goes to the function where it was invoked.After execution, it comes back to a point from where it left the execution and starts executing next lines.
To create a coroutine ,
1.we simply create a method that returns IEnumerator.
2.It also needs a yield return statement.
IEnumerator spawning() {
// Your code here…
yield return null;
}
Calling a Coroutine
We just created a coroutine named spawning. To call the coroutine, we use the StartCoroutine method.
StartCoroutine(spawning());
Update runs every frame & its lifecycle cannot be controlled but we can control the lifecycle of a coroutine. We can stop the execution on-demand and pause the execution using yield operator.
Let’s see how you can spawn gameObject using Coroutine
Create an Empty object and name it as Spawning, in the script folder create Spawner script. Attach the Script to the Spawning gameObject .Create the code as shown below
We can randomize the position of spwaning , set the minimum and maximum value for spawning .Get the random value from min to max point using Random.Range(mix,max) ,apply that position to the Instantiate function.