unity3d学习(二)yield与StartCoroutine

首先,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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值