C#中的yield return与Unity中的Coroutine(协程)(下)

Posted 实现梦想与回忆的,叫做现在

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#中的yield return与Unity中的Coroutine(协程)(下)相关的知识,希望对你有一定的参考价值。

Unity中的Coroutine(协程)

估计熟悉Unity的人看过或者用过StartCoroutine()

假设我们在场景中有一个UGUI组件, Image:

技术分享

将以下代码绑定到Image

技术分享
 1 using UnityEngine;
 2 using System.Collections;
 3 using System.Threading;
 4 using UnityEngine.UI;
 5 
 6 public class CoroutineDemo : MonoBehaviour {
 7 
 8     // Use this for initialization
 9     void Start () {
10     
11         Debug.Log (Thread.CurrentThread.Name + ": Start begin. fCount=" +  + Time.renderedFrameCount);
12 
13 
14         this.StartCoroutine (exeuteCoroutine());
15     }
16     
17     // Update is called once per frame
18     void Update () {
19         
20         Debug.Log (Thread.CurrentThread.Name + ": Update(): fCount=" + Time.renderedFrameCount);
21     }
22 
23      
24     public IEnumerator exeuteCoroutine(){
25         Debug.Log (Thread.CurrentThread.Name + ": Before yield return A, fCount=" + Time.renderedFrameCount);
26         //yield return new WaitForSeconds(1);
27         yield return "A";
28 //        yield return "C";
29 //        yield return "D";
30         Debug.LogError (Thread.CurrentThread.Name + ": After yield return A, fCount=" + Time.renderedFrameCount);
31     }
32 
33     IEnumerator LoadImage()
34     {
35         WWW www=new WWW("http://pic89.nipic.com/file/20160211/22571617_214730734684_2.jpg");
36         Image img = this.gameObject.GetComponent<Image> ();
37 
38         Debug.Log("Before yield return: " + www.url + " is done? " + www.isDone + ", rf=" + Time.renderedFrameCount);
39 
40         yield return www;
41 
42         Debug.Log("After yield return, " + www.url + " is done? " + www.isDone + ", rf=" + Time.renderedFrameCount);
43         Rect spriteRect = new Rect (0, 0, www.texture.width, www.texture.height);
44         Sprite imageSprite = Sprite.Create (www.texture, spriteRect, new Vector2 (0.5f, 0.5f));
45         img.sprite = imageSprite;
46 
47     }
48 }
View Code

运行之后日志输出:

 

以上是关于C#中的yield return与Unity中的Coroutine(协程)(下)的主要内容,如果未能解决你的问题,请参考以下文章

yield学习续:yield return迭代块在Unity3D中的应用——协程

由C# yield return引发的思考

C# yield return 枚举器,从部分继续

Unity3D/C#Unity3D中的Coroutine详解

C#中yield return用法

es6 中的generator函数控制流程