unity3D中協程IEnumerator使用
阿新 • • 發佈:2018-12-15
練習 :物體本身是白色,當點選攻擊按鈕後,物體變紅,1秒後變回原來的顏色
public class ChangeColor : MonoBehaviour { private Color oldColor; private MeshRenderer render; private void Start(){ render = this.GetComponent<MeshRenderer>(); oldColor = render.material.color; } private void Damage(){ StartCoroutine("ChangeColorFunc"); //呼叫 // StartCoroutine(ChangeColorFunc()); //函式引數呼叫 // StopCoroutines();只能停止一字串啟動的協程 } private IEnumerator ChangeColorFunc() { //定義協程 render.material.color = Color.red; yield return new WaitForSeconds(1); render.material.color = oldColor; } private void OnGUI() { if (GUILayout.Button("攻擊")) Damage(); } }
多個路點巡邏:每到一點等待一段時間再繼續巡邏
/// <summary> /// 路點巡邏 /// </summary> public class PathTest : MonoBehaviour{ public Transform[] points;//路點 public float speed = 5; private bool loop = true; private void OnGUI() {//找到一個路點等待2秒,並且可以迴圈巡邏 if (GUILayout.Button("開始")) StartCoroutine(MoveToPath()); else if (GUILayout.Button("停止")) StopAllCoroutines();//停止本物件中所有協程 } private IEnumerator MoveToPath(){ do { foreach (var point in points) { //協程巢狀 //找到目標點後再找下一個點,等待MoveToTarget()方法執行結束後再啟用協程 yield return StartCoroutine(MoveToTarget(point.position)); yield return new WaitForSeconds(2); } } while (loop); } //找目標點,不是一次,而是分多次,所以此處適宜用協程 private IEnumerator MoveToTarget(Vector3 target){ while (transform.position != target){ transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime); yield return new WaitForFixedUpdate(); } //yield return new WaitForSeconds(2); } }