Courotine也称为协同程序或者协程,协同程序可以和主程序并行运行,和多线程类似。协同程序可以用来实现让一段程序等待一段时间后继续运行效果,例如:执行步骤1,等待3秒;执行步骤2,等待某个条件为true;执行步骤3.。。。。
unity与协同程序有关的函数有:
1.StartCouroutine 启动一个协同程序 2.StopCouroutine 终止一个协同程序 3.StopAllCoroutines 终止所有协同程序 4.WaitForSeconds 等待若干秒 5.WaitForFixedupdate 等待直到下一次FixedUpdate调用
在c#中使用Couroutine应该注意的几点:
1.启动Couroutine,用StartCouroutine这种方法,这种方法是MonoBehavior的方法
2.启动这种方法的返回值必须是IEnumerator
3.IEnumerator 函数必须出现 yield return new WaitForSeconds等字样
下面是用它来实现物体沿着正方形循环移动的一个例子:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
private Vector3 v = new Vector3();
private float speed = 0.0375f;
// Use this for initialization
void Start()
{
StartCoroutine(Routine());
}
// Update is called once per frame
void FixedUpdate () {
transform.position += v;
}
IEnumerator Routine()
{
v.z = speed;
v.x = 0;
yield return new WaitForSeconds(3f);
v.z = 0;
v.x = -speed;
yield return new WaitForSeconds(3f);
v.z = -speed;
v.x = 0;
yield return new WaitForSeconds(3f);
v.z = 0;
v.x = speed;
yield return new WaitForSeconds(3f);
StartCoroutine(Routine());//函数递归调用,达到循环移动的效果
}
}
不用协同时可以这样写:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class theother : MonoBehaviour {
private Vector3 v=new Vector3();
private float speed=0.03f;
// Use this for initialization
void Start () {
v.z = speed;
v.x = 0;
}
// Update is called once per frame
void Update () {
transform.position += v;
if (transform.position.z > 3)
{
transform.position = new Vector3(0, transform.position.y, 3);
v.z = 0;
v.x = -speed;
}
if (transform.position.x < -3)
{
transform.position = new Vector3(-3, transform.position.y, 3);
v.z = -speed;
v.x = 0;
}
if (transform.position.z < 0)
{
transform.position = new Vector3(-3, transform.position.y, 0);
v.z = 0;
v.x = speed;
}
if (transform.position.x > 0)
{
transform.position = new Vector3(0, transform.position.y, 0);
v.z = speed;
v.x = 0;
}
}
}
以上都是以前写的,最近看到两篇关于协程的文章,国外写的,比较有趣,把链接发过来吧:
https://unitygem.wordpress.com/coroutines/
https://unitygem.wordpress.com/coroutine-usage-invoke-delay/