Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Unity3D StartCoroutine calls a function, when does that function return?

Tags:

c#

unity3d

I know that Unity3D StartCoroutine calls a function which runs on the same thread as StartCoroutine, but when does the called function return back to the original caller?

like image 986
JohnnyLambada Avatar asked Sep 17 '13 17:09

JohnnyLambada


People also ask

What is StartCoroutine in Unity?

A coroutine is a function that allows pausing its execution and resuming from the same point after a condition is met. We can say, a coroutine is a special type of function used in unity to stop the execution until some certain condition is met and continues from where it had left off.

What does yield return do Unity?

The yield return statement is special; it is what actually tells Unity to pause the script and continue on the next frame.

Can coroutines return a value?

A Unity Coroutine is a C# generator. Every time you call yield in a generator you are "returning" a value. That's what they are intended to do, generate values.


1 Answers

I looked around the internet for a good Unity3D Coroutine example and couldn't find a complete one. There is a great explanation by UnityGems, but even their example is incomplete. So I wrote my own example.

This:

using UnityEngine;
using System.Collections;
public class MainCamera: MonoBehaviour {
  void Start () {
    Debug.Log ("About to StartCoroutine");
    StartCoroutine(TestCoroutine());
    Debug.Log ("Back from StartCoroutine");
  }
  IEnumerator TestCoroutine(){
    Debug.Log ("about to yield return WaitForSeconds(1)");
    yield return new WaitForSeconds(1);
    Debug.Log ("Just waited 1 second");
    yield return new WaitForSeconds(1);
    Debug.Log ("Just waited another second");
    yield break;
    Debug.Log ("You'll never see this"); // produces a dead code warning
  }
}

Produces this output:

About to StartCoroutine
about to yield return WaitForSeconds(1)
Back from StartCoroutine
Just waited 1 second
Just waited another second
like image 174
JohnnyLambada Avatar answered Nov 15 '22 19:11

JohnnyLambada