Unity3D之协程(Coroutines & Yield )

http://blog.csdn.net/jjiss318/article/details/7447421

yield return可以看做是一种特殊的return,会返回到父类继续执行,但是yield return后面的类型或方法会有一个执行条件,当条件满足时会回调包含yield的子函数,例如下面代码

例1:

using UnityEngine;
using System.Collections;

public class YieldExample : MonoBehaviour {

	// Use this for initialization
	void Start () 
    {
        print("Starting:" + Time.time);  
        StartCoroutine(DelayTime(12.0f));
        print("<span style="color: rgb(255, 0, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(245, 250, 226);">Before WaiAndPrint</span>:" + Time.time); ;
	}
	
	// Update is called once per frame
	void Update () {
       
	}

    IEnumerator DelayTime(float waitTime)
    {
        yield return new WaitForSeconds(waitTime); //等待3秒
        print("WaitAndPrint:" + Time.time);      
    }

}

在执行yield return new WaitForSeconds(waitTime)时暂停的条件没有满足,故返回到start函数中继续执行,直到满足条件后再回调WaitAndPrint,所以输出为:
Starting:0
Before WaiAndPrint:0
WaitAndPrint:2.12291

using UnityEngine;
using System.Collections;

public class YieldExample : MonoBehaviour {

	// Use this for initialization
    IEnumerator Start() 
    {
        print("Starting:" + Time.time);
        yield return StartCoroutine(DelayTime(12.0f));
        print("done:" + Time.time); 
	}
	
	// Update is called once per frame
	void Update () {
       
	}

    IEnumerator DelayTime(float waitTime)
    {
        yield return new WaitForSeconds(waitTime); //等待3秒
        print("WaitAndPrint:" + Time.time);      
    }

}

因为start为顶级函数,所以会阻塞在这里,直到StartCoroutine(WaitAndPrint(2.0F))执行完毕,输出为:

starting:0
WaitAndPrint:2.00315
done:2.00315




你可能感兴趣的:(Unity3D之协程(Coroutines & Yield ))