协同程序c#版,Coroutines in Unity3d (C# version)

1 reply [最后一篇]
u8
User offline. Last seen 1 年 6 周 ago. Offline
超级管理员
Joined: 09/05/2009
Points: 2119

Coroutines in C# work the same way that they do in Javascript (UnityScript), the only difference is that they require more typing (they have a slightly more complicated syntax). You should see the blog post on Javascript coroutines first.

Here, I present the differences:

Coroutines must have the IEnumerator return type:

1    IEnumerator MyCoroutine()
2    {
3        //This is a coroutine
4    }

To invoke a coroutine you must do it using the StartCoroutine method:

01    public class MyScript : MonoBehaviour
02    {
03        void Start()
04        {
05            StartCoroutine(MyCoroutine());
06        }
07     
08        IEnumerator MyCoroutine()
09        {
10            //This is a coroutine
11        }
12    }

The yield statement becomes yield return in C# :

1    IEnumerator MyCoroutine()
2    {
3        DoSomething();
4        yield return 0; //Wait one frame, the 0 here is only because we need to return an IEnumerable
5        DoSomethingElse();
6    }

Remember that we need to return an IEnumerable, so the Javascript yield; becomes yield return 0; in C#

Also, since C# requires you to use the new operator to create objects, if you want to use WaitForSeconds you have to use it like this:

1    IEnumerator MyCoroutine()
2    {
3        DoSomething();
4        yield return new WaitForSeconds(2.0f);  //Wait 2 seconds
5        DoSomethingElse();
6    }

Marcus
User offline. Last seen 51 周 2 天 ago. Offline
注册用户
Joined: 02/24/2011
Points: 10

除了script reference,还可以参考http://www.blog.silentkraken.com/2010/01/23/coroutines-in-unity3d-c-version/

加深认识。在c#与javascript中写法也不一样。c#本身在.net2.0起就有一个yield, 作用同Python,Java也有一个,作用缺不一样。最好是都看看。

总体来说应该是异步+同步用的吧, c#本身的yield return/yield break却是针对IEnumerable接口做枚举用的(与3D绘图无关)