Unity3D协程(一)

来源:转载




协程介绍


Unity的协程系统是基于C#的一个简单而强大的接口 ,IEnumerator,它允许你为自己的集合类型编写枚举器。


yield return是“停止执行方法,并且在下一帧从这里重新开始”。

简单计时器实例:StartCoroutine()并没有给它传入参数,但是这个方法调用了它自己(这是通过传递CoroutineMethod的return返回值来实现的)


// Use this for initialization
void Start ()
{
StartCoroutine(CoroutineMethod());
}IEnumerator CoroutineMethod ()
{
for (float timer = 3; timer >= 0; timer -= Time.deltaTime) {
yield return 0;
}
Debug.Log ("This message appears after 3 seconds!");
}

hello实例:


//This will say hello 5 times, once each frame for 5 frames
IEnumerator SayHelloFiveTimes ()
{
yield return 0;
Debug.Log ("Hello");
yield return 0;
Debug.Log ("Hello");
yield return 0;
Debug.Log ("Hello");
yield return 0;
Debug.Log ("Hello");
yield return 0;
Debug.Log ("Hello");
}
//This will do the exact same thing as the above function!
IEnumerator SayHello5Times ()
{
for (int i = 0; i < 5; i++) {
Debug.Log ("Hello");
yield return 0;
}
}

开始和终止协程


//If you start a Coroutine by name...
StartCoroutine("FirstTimer");
StartCoroutine("SecondTimer");
//You can stop it anytime by name!
StopCoroutine("FirstTimer");
//You can stop all anytime!
StopAllCoroutines ();



分享给朋友:
您可能感兴趣的文章:
随机阅读: