Coroutine in C# : How to use in your Unity Game

What is Coroutine


Unity Coroutine interview question and uses

Acoroutine is a kind of function that use to perform some event occurring in a sequence. It may be performing animation procedure or reducing scale continuously over time. When we call a function it complete its execution and give control to its caller or where it called, but in case of coroutine it execute and pause further execution and return control to it's caller and after certain condition it again start execution from same point.  In unity coroutine is use widely to perform some animation or to move object gradually overtime.

There is a example of coroutine : 

Image thisImage;

IEnumerator Fade() 
{
   int i=0;
   Vector2 pos;

    while(i<50)
    {
         pos.x = Mathf.Lerp(pos.x, 5, 3*Time.deltaTime );
         yield return new WaitForSecond(.2f);
          i++;
    }
}

In the above Example we are changing value overtime, SO if we are moving objects horizontal position over time we can use coroutine.


Best uses of Coroutine in Unity games

1. Detecting some condition with fixed interval of time.
2. Performing animation over time.
3. To lerp value over time.
4. For instantiating bullet, Enemy and any effect with fixed period of time.
5. Updating UI elements over time.
6. Best alternative for Update function if we don't want to update things in each frame.

Questions on Coroutine

1. What is coroutine, why we use it. ?
2. How we will execute some code for function after particular interval of time. ?
3. How we can give some sec. delay in unity game. ? 
4. What is IEnumerator in C#. ?
5. How to start and stop coroutine. ?
6. what is yield in coroutine ?