協(xié)程,又稱微線程,纖程。英文名Coroutine。
子程序,或者稱為函數(shù),在所有語(yǔ)言中都是層級(jí)調(diào)用,比如A調(diào)用B,B在執(zhí)行過(guò)程中又調(diào)用了C,C執(zhí)行完畢返回,B執(zhí)行完畢返回,最后是A執(zhí)行完畢。
因?yàn)閰f(xié)程是一個(gè)線程執(zhí)行,那怎么利用多核CPU呢?最簡(jiǎn)單的方法是多進(jìn)程+協(xié)程,既充分利用多核,又充分發(fā)揮協(xié)程的高效率,可獲得極高的性能。
1、參數(shù)說(shuō)明:
IEnumerator:協(xié)同程序的返回值類型;
yield return:協(xié)同程序返回 xxxxx;
new WaitForSeconds (秒數(shù)):實(shí)例化一個(gè)對(duì)象,等待多少秒后繼續(xù)執(zhí)行。 這個(gè) Task3()的作用就是等待兩秒后,繼續(xù)執(zhí)行任務(wù) 3.
2.開(kāi)啟協(xié)同程序
StartCoroutine(“協(xié)同程序方法名”);
這個(gè) StartCoroutine 有三種重載形式,目前先只介紹這一種。
3.停止協(xié)同程序
StopCoroutine(“協(xié)同程序方法名”);
這個(gè) StopCoroutine 也有三種重載形式,目前先只介紹這一種。
使用協(xié)程,實(shí)現(xiàn)一個(gè) ??,移動(dòng)。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxMove : MonoBehaviour {
private Vector3 v = new Vector3 ();
private float speed = 0.0375f;
void Start () {
v.z = speed;
StartCoroutine (Routine());
}
void Update () {
}
void FixedUpdate()
{
transform.position += v;
}
//協(xié)程
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());
}
}

4.00.11.png