首先,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/
本文深入探讨了C#中的yield关键字用于创建迭代集合的功能,并解释了其在循环打印数学运算结果的应用。同时,文章详细阐述了Unity中Coroutine的概念、如何使用StartCoroutine方法暂停与恢复协程执行,以及Coroutine与线程之间的区别。通过实例演示了如何在Unity环境中利用Coroutine实现高效、流畅的游戏逻辑控制。
982

被折叠的 条评论
为什么被折叠?



