unity3d学习(二)yield与StartCoroutine
sshong 发表于2013年2月3日 11:51:54 更新于2013年2月3日 11:51:54
原文

首先,yield是c#2.0的语法,目的是用来创建一个迭代集合。

每yield return一次相当于调用了一次moveNext,并返回current。

以下面例子为例,会循环打印n的1到m次幂的值。

using System;
using System.Collections;

namespace testYield
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Console.WriteLine ("Hello World!");
            foreach(int i in MyYield.pow(2, 4))
            {
                Console.WriteLine("{0}", i);
            }
        }
    }
    class MyYield
    {
        public static IEnumerable pow(int basic, int power)
        {
            int start = 1;
            int result = 1;
            do
            {
                result = result * basic;
                yield return result;
                start++;
            }
            while(start <= power);
        }
    }
}
再者:StartCoroutine是unity的monoBehavior中的一个方法

官方文档解释:
The execution of a coroutine can be paused at any point using the yield statement. The yield return value specifies when the coroutine is resumed. Coroutines are excellent when modelling behaviour over several frames. Coroutines have virtually no performance overhead. StartCoroutine function always returns immediately, however you can yield the result. This will wait until the coroutine has finished execution.

另外找到一篇帖子讲述Coroutine和Thread的区别:

协同:在unity的主线程上,每一帧都去检查yield条件满足,直到yield条件满足,协同才会继续执行下去。

线程:线程则是同时运行的,unity不允许在主线程以外的其他线程去访问unity任何api;

What happens with a coroutine is that it is run on the main thread every frame and executes until it does a yield - then it will suspend until the yield condition is met. That yield condition is tested every frame and when the condition is met the code in your coroutine resumes. A thread effectively runs at the same time as other code (this is only true when you have multiple cores). Unity cannot support accessing its API from anything apart from the main thread.

参见:http://answers.unity3d.com/questions/280597/new-thread-vs-startcoroutine.html


另外,所有IEnumerator类型函数必须使用”StartCoroutine”这个函数触发,不能单独使用,

参见:http://spotlightor.com/blog/tutorial/unity3d_implement_coroutines_yield_in_csharp/
标签:unity3d分类:Unity3d阅读:3811
评论
暂无评论
添加评论
您的大名,限长10汉字,20英文(*)
电子信箱(*)
您的网站
正文,限长500汉字,1000英文(*)
验证码(*) 单击刷新验证码
联系我
博客订阅