MonoBehaviour.StartCoroutine

来源:互联网 发布:广州游戏美工招聘 编辑:程序博客网 时间:2024/05/09 17:20

function StartCoroutine (routine : IEnumerator) : Coroutine

Description

Starts a coroutine.

The execution of a coroutine can be paused at any point using the yield statement. The yield return value specifies when the coroutine is resumed. Coroutines are excellent when modelling behaviour over several frames. Coroutines have virtually no performance overhead. StartCoroutine function always returns immediately, however you can yield the result. This will wait until the coroutine has finished execution.

When using JavaScript it is not necessary to use StartCoroutine, the compiler will do this for you. When writing C# code you must call StartCoroutine.

C#
using UnityEngine;using System.Collections;public class example : MonoBehaviour {    void Start() {        print("Starting " + Time.time);        StartCoroutine(WaitAndPrint(2.0F));        print("Before WaitAndPrint Finishes " + Time.time);    }    IEnumerator WaitAndPrint(float waitTime) {        yield return new WaitForSeconds(waitTime);        print("WaitAndPrint " + Time.time);    }}

Another Example:
C#
using UnityEngine;using System.Collections;public class example : MonoBehaviour {    IEnumerator Start() {        print("Starting " + Time.time);        yield return StartCoroutine(WaitAndPrint(2.0F));        print("Done " + Time.time);    }    IEnumerator WaitAndPrint(float waitTime) {        yield return new WaitForSeconds(waitTime);        print("WaitAndPrint " + Time.time);    }}

function StartCoroutine (methodName : String, value : object = null) : Coroutine

Description

Starts a coroutine named methodName.

In most cases you want to use the StartCoroutine variation above. However StartCoroutine using a string method name allows you to use StopCoroutine with a specific method name. The downside is that the string version has a higher runtime overhead to start the coroutine and you can pass only one parameter

C#
using UnityEngine;using System.Collections;public class example : MonoBehaviour {    IEnumerator Start() {        StartCoroutine("DoSomething", 2.0F);        yield return new WaitForSeconds(1);        StopCoroutine("DoSomething");    }    IEnumerator DoSomething(float someParameter) {        while (true) {            print("DoSomething Loop");            yield return null;        }    }}
原创粉丝点击