Coroutine 协同程序

Namespace: UnityEngine

Inherits from: YieldInstruction

Description 描述

MonoBehaviour.StartCoroutine returns a Coroutine. Instances of this class are only used to reference these coroutines and do not hold any exposed properties or functions.

MonoBehaviour.StartCoroutine返回一个Coroutine。这个类的实例仅用于引用这些协同程序,并不持有任意暴露的变量或函数。

A coroutine is a function that can suspend its execution (yield) until the given given YieldInstruction finishes.

coroutine是一个能暂停执行(yield)的函数,直到给定的YieldInstruction完成。

JavaScript:

// - prints "Starting 0.0"

// - prints "WaitAndPrint 5.0"

// - prints "Done 5.0"

 

print ("Starting " + Time.time); // Start function WaitAndPrint as a coroutine yield WaitAndPrint(); print ("Done " + Time.time);

 

function WaitAndPrint () { // suspend execution for 5 seconds yield WaitForSeconds (5); print ("WaitAndPrint "+ Time.time); } 

C#:

using UnityEngine;

using System.Collections;

 

public class ExampleClass : MonoBehaviour {

    IEnumerator WaitAndPrint() {

        yield return  WaitForSeconds(5);

        print("WaitAndPrint " + Time.time);

    }

    IEnumerator Example() {

        print("Starting " + Time.time);

        yield return WaitAndPrint();

        print("Done " + Time.time);

    }

}