C#中Yield使用方法小结,可能理解的不正确,后续修改。
yield return可以看做是一种特殊的return,会返回到父类继续执行,但是yield return后面的类型或方法会有一个执行条件,当条件满足时会回调包含yield的子函数,例如下面代码
例1:
- void Start () {
- print("Starting:" + Time.time);
- StartCoroutine(WaitAnPrint(2.0F));
- print("Before WaiAndPrint:" + Time.time);
- }
- IEnumerator WaitAndPrint(float waitTime)
- {
- yield return new WaitForSeconds(waitTime);
- print("WaitAndPrint:" + Time.time);
- }
在执行yield return new WaitForSeconds(waitTime)时暂停的条件没有满足,故返回到start函数中继续执行,直到满足条件后再回调WaitAndPrint,所以输出为:
- Starting:0
- Before WaiAndPrint:0
- WaitAndPrint:2.12291
例2:
- 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);
- }
因为start为顶级函数,所以会阻塞在这里,直到StartCoroutine(WaitAndPrint(2.0F))执行完毕,输出为:
- starting:0
- WaitAndPrint:2.00315
- done:2.00315
阅读(6915) | 评论(0) | 转发(0) |