Unity中的Coroutine(协程)

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

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

将以下代码绑定到Image

 using UnityEngine;
using System.Collections;
using System.Threading;
using UnityEngine.UI; public class CoroutineDemo : MonoBehaviour { // Use this for initialization
void Start () { Debug.Log (Thread.CurrentThread.Name + ": Start begin. fCount=" + + Time.renderedFrameCount); this.StartCoroutine (exeuteCoroutine());
} // Update is called once per frame
void Update () { Debug.Log (Thread.CurrentThread.Name + ": Update(): fCount=" + Time.renderedFrameCount);
} public IEnumerator exeuteCoroutine(){
Debug.Log (Thread.CurrentThread.Name + ": Before yield return A, fCount=" + Time.renderedFrameCount);
//yield return new WaitForSeconds(1);
yield return "A";
// yield return "C";
// yield return "D";
Debug.LogError (Thread.CurrentThread.Name + ": After yield return A, fCount=" + Time.renderedFrameCount);
} IEnumerator LoadImage()
{
WWW www=new WWW("http://pic89.nipic.com/file/20160211/22571617_214730734684_2.jpg");
Image img = this.gameObject.GetComponent<Image> (); Debug.Log("Before yield return: " + www.url + " is done? " + www.isDone + ", rf=" + Time.renderedFrameCount); yield return www; Debug.Log("After yield return, " + www.url + " is done? " + www.isDone + ", rf=" + Time.renderedFrameCount);
Rect spriteRect = new Rect (, , www.texture.width, www.texture.height);
Sprite imageSprite = Sprite.Create (www.texture, spriteRect, new Vector2 (0.5f, 0.5f));
img.sprite = imageSprite; }
}

运行之后日志输出(Error 日志是为了明显,才这么打的):

fCount 代表的是当前已经渲染的帧数,发现, yield return 之后的代码, 是在yield return 之后的一帧执行的。

如果yield return 之后换成 new WaitForSeconds(1); yield之后的代码就在1秒后执行。

看一下MonoBehaviour的生命周期:

发现, 在StartCortinue()传入的方法中, 可以yield return 的类型有:

yield return null;

yield return WaitForSeconds(); (实际上, 继承自 YieldInstruction的都可以)

yield return WWW;

如果将例子中的代码改成加载图片:

     void Start () {
Debug.Log (Thread.CurrentThread.ManagedThreadId + ": Start begin. fCount=" + + Time.renderedFrameCount);
this.StartCoroutine (LoadImage());
}
     IEnumerator LoadImage()
{
WWW www=new WWW("http://pic89.nipic.com/file/20160211/22571617_214730734684_2.jpg");
Image img = this.gameObject.GetComponent<Image> (); Debug.Log("Before yield return: " + www.url + " is done? " + www.isDone + ", rf=" + Time.renderedFrameCount); yield return www; Debug.Log("After yield return, " + www.url + " is done? " + www.isDone + ", rf=" + Time.renderedFrameCount);
Rect spriteRect = new Rect (, , www.texture.width, www.texture.height);
Sprite imageSprite = Sprite.Create (www.texture, spriteRect, new Vector2 (0.5f, 0.5f));
img.sprite = imageSprite; }

通过输出日志, 你会发现, yield return www;之后的代码, 是在www.isDone之后, 也就是图片加载完毕之后才执行的!

Before yield return: http://pic89.nipic.com/file/20160211/22571617_214730734684_2.jpg is done? False, rf=1
UnityEngine.Debug:Log(Object)
<LoadImage>c__Iterator6:MoveNext() (at Assets/Scripts/CoroutineDemo.cs:)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
CoroutineDemo:Start() (at Assets/Scripts/CoroutineDemo.cs:) After yield return, http://pic89.nipic.com/file/20160211/22571617_214730734684_2.jpg is done? True, rf=34
UnityEngine.Debug:Log(Object)
<LoadImage>c__Iterator6:MoveNext() (at Assets/Scripts/CoroutineDemo.cs:)

总结:

yield return 搭配上WaitForSecond, WWW, 可以达到延时执行的效果。

但是, 特别注意的是, StartCoroutine()并没有开启新的线程来执行, 还是执行在与Start(), Update()相同的主线程中!

C#中的yield return与Unity中的Coroutine(协程)(下)的更多相关文章

  1. C#中的yield return与Unity中的Coroutine(协程)(上)

    C#中的yield return C#语法中有个特别的关键字yield, 它是干什么用的呢? 来看看专业的解释: yield 是在迭代器块中用于向枚举数对象提供值或发出迭代结束信号.它的形式为下列之一 ...

  2. 可惜Java中没有yield return

    项目中一个消息推送需求,推送的用户数几百万,用户清单很简单就是一个txt文件,是由hadoop计算出来的.格式大概如下: uid caller 123456 12345678901 789101 12 ...

  3. C#中的yield return用法演示源码

    下边代码段是关于C#中的yield return用法演示的代码. using System;using System.Collections;using System.Collections.Gene ...

  4. Unity之"诡异"的协程

    为什么说是诡异的协程呢?首先从一个案例说起吧,示例如下: 游戏目标:让小车进入到对应颜色屋子里,即可获得一分.(转弯的道路可控)   为了让小车能够平滑转弯,小车的前进方向需要和车子的位置与圆心组成的 ...

  5. C#中的yield return

    4.1 迭代器块 一个迭代器块(iterator block)是一个能够产生有序的值序列的块.迭代器块和普通语句块的区别就是其中出现的一个或多个yield语句. yield return语句产生迭代的 ...

  6. unity, yield return new WaitForSeconds(waitTime) 在 Time.timeScale=0下卡死

    例如下面代码: IEnumerator f(){ Time.timeScale = 0; float waitTime=2; yield return new WaitForSeconds (wait ...

  7. Android中的Coroutine协程原理详解

    前言 协程是一个并发方案.也是一种思想. 传统意义上的协程是单线程的,面对io密集型任务他的内存消耗更少,进而效率高.但是面对计算密集型的任务不如多线程并行运算效率高. 不同的语言对于协程都有不同的实 ...

  8. Unity脚本编程之——协程(Coroutine)

    本文翻译自Unity官方文档:https://docs.unity3d.com/Manual/Coroutines.html 专有名词: Coroutine 协程 Alpha 不透明度 当你调用一个函 ...

  9. 【Unity笔记】使用协程(Coroutine)异步加载场景

    using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; using System; public ...

随机推荐

  1. jQuery form插件的使用--处理server返回的JSON, XML,HTML数据

    详细代码: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> & ...

  2. 用PowerDesigner将SQL语句生成实体类

    1.首先打开PowerDesigner,点击左上角“File”—>"Reverse Engineer"—>"Database..." 2.选择数据库 ...

  3. 字符串_KMP算法(求next[]模板 hdu 1711)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1711 问题描述:给两个序列a,b,长度分别为n,m(1<=n<=1000000,1< ...

  4. 20150912华为机考1之"输入一个字符串,将其中出现次数最多的字符输出"

    不吐槽华为的服务器了,直接上正文 输入:字符串(英文字母),长度不超过128 输出:出现频率最高的字母 思路写在注释文档 /* Input a string * Output the most fre ...

  5. 【读书笔记《Android游戏编程之从零开始》】3.Android 游戏开发常用的系统控件(Button、Layout、ImageButton)

    3.1 Button Button这控件不用多说,就是一个按钮,主要是点击后进行相应事件的响应. 给组件添加ID属性:定义格式为 android:id="@+id/name",这里 ...

  6. codeforces 713A A. Sonya and Queries(状态压缩)

    题目链接: A. Sonya and Queries time limit per test 1 second memory limit per test 256 megabytes input st ...

  7. Unity 跑酷Demo难题总结

    问题1:路面拼接处理 在拼接路的时候,如果两个路挨的太近就会出现贴图闪烁,如下所示 解决办法 如果把路改小就会出现断层,但不会出现贴图闪烁 PS:我是把贴图放在Cube上的,所以路是有厚度. 附注 刚 ...

  8. [转] 国外程序员整理的 C++ 资源大全

    关于 C++ 框架.库和资源的一些汇总列表,由 fffaraz 发起和维护. 内容包括:标准库.Web应用框架.人工智能.数据库.图片处理.机器学习.日志.代码分析等. 标准库 C++标准库,包括了S ...

  9. PHP简单post验证绕过

    if($_POST[user] && $_POST[pass]) { $conn = mysql_connect("*******", "****&quo ...

  10. 6月27日 OGDF不同的布局算法

    检查不同布局算法 备注 CircularLayout 可以非连通 FastMultipoleMultilevelEmbedder    FMMMLayout   可以非连通 StressMajoriz ...