Unity

When you write something in the update( ) method, it runs to its completion before moving ahead with other instructions.

You must wonder that if there are 1000 game objects in your game at a time, how many updates will need to be done every frame. Does it seem inefficient and a power-hungry task? Yes, it is.

However, there are some tasks that you’d like to scatter over a period of time and not in every frame such as procedural animation. We can call them parallel tasks and it's in the best interest to not put them in the update method.

Unity provides an in-house tool called a coroutine that accommodates this.

The definition given by Unity is as followed.

A coroutine is like a function that has the ability to pause execution and return control to Unity but then to continue where it left off on the following frame.

  • Please note that when you declare a coroutine, it must be of a type IEnumerator and contain a yield statement in it.
  • A coroutine gets called through the startCoroutine(Coroutine( )) method.

Let us get into Visual Studio to write some code.

  • First, let us disable the mesh renderer to disable the presence of our cube in the game view.
  • Second, we write a coroutine that waits for a second after we press the spacebar key and then enables the mesh renderer.

To make it a little more interesting, let us add one more coroutine that changes the color of our cube with each spacebar input.

  • First, declare a variable of type Color.
  • Use the GetComponent method to get the current color of the cube’s material.
  • Declare a coroutine and use the color variable to store random color values in RGBa format. (Alpha remains 1 by default if we do not provide a value.)
  • Assign the new color to the material by using the GetComponent( ) method.

Please observe that to call the coroutine, we have used StartCoroutine( ) methods in the update( ) method.

As you can see with each input from the spacebar, the cube gets hidden for a second & comes back with a brand new color.

Please note that the update method would have continued working on further instruction if there were, & this effect would have still taken place since it's running in parallel to the main execution.

Thank you very much

Work in Progress.