Yield使用方法

6895阅读 0评论2011-07-20 matthew_1983
分类:嵌入式

C#中Yield使用方法小结,可能理解的不正确,后续修改。
yield return可以看做是一种特殊的return,会返回到父类继续执行,但是yield return后面的类型或方法会有一个执行条件,当条件满足时会回调包含yield的子函数,例如下面代码
例1:
  1. void Start () {
  2.         print("Starting:" + Time.time);
  3.         StartCoroutine(WaitAnPrint(2.0F));
  4.         print("Before WaiAndPrint:" + Time.time);
  5.     }
  6. IEnumerator WaitAndPrint(float waitTime)
  7.     {
  8.         yield return new WaitForSeconds(waitTime);
  9.         print("WaitAndPrint:" + Time.time);    
  10.     }

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

  1. Starting:0
  2. Before WaiAndPrint:0
  3. WaitAndPrint:2.12291

例2:

  1. IEnumerator Start()
  2.     {
  3.         print("starting:" + Time.time);
  4.         yield return StartCoroutine(WaitAndPrint(2.0F));
  5.         print("done:" + Time.time);
  6.     }
  7. IEnumerator WaitAndPrint(float waitTime)
  8.     {
  9.         yield return new WaitForSeconds(waitTime);
  10.         print("WaitAndPrint:" + Time.time);    
  11.     }

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

  1. starting:0
  2. WaitAndPrint:2.00315
  3. done:2.00315
上一篇:Unity3d CarSmoothFollow
下一篇:Security Sandbox of the Webplayer in U3D