IEnumerator DelayCoroutine() { // work before delay yield return new WaitForSeconds(<time value to delay>); // work after delay } StartCoroutine(DelayCoroutine());
IEnumerator CountSeconds() { int seconds = 0; while (true) { yield return new WaitForSeconds(1f); seconds++; Debug.Log(seconds + " seconds have passed since the Coroutine started."); } }
void Start() { //输出5次Hello,间隔1秒 c = StartCoroutine(RepeatMessage(5, 1, "Hello")); } IEnumerator RepeatMessage(int count, float frequency, string message) { for (int i = 0; i < count; i++) { Debug.Log(message); yield return new WaitForSeconds(frequency); } }
嵌套的协程
协程最强大的一个功能就是它们可以通过使用yield语句来相互嵌套。
1 2 3 4 5 6 7 8
IEnumerator SaySomeThings() { Debug.Log("The routine has started"); yield return StartCoroutine(RepeatMessage(1, 1f, "Hello")); Debug.Log("1 second has passed since the last message"); yield return StartCoroutine(RepeatMessage(1, 2.5f, "Hello")); Debug.Log("2.5 seconds have passed since the last message"); }
控制对象行为的例子
运动到某一位置
在Inspector面板中设置目标位置和运动速度,在游戏开始时将一个物体移动到目标位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public Vector3 targetPosition; public float moveSpeed=5; void Start() { c = StartCoroutine(MoveToPosition(targetPosition)); } IEnumerator MoveToPosition(Vector3 target) { while (transform.position != target) { transform.position = Vector3.MoveTowards(transform.position, target, moveSpeed*Time.deltaTime); yield return 0; } }
public List<Vector3> path; IEnumerator MoveOnPath(bool loop) { do { foreach (var point in path) yield return StartCoroutine(MoveToPosition(point)); } while (loop); }
public class CorTest2 : MonoBehaviour { int i = 0;//update中判断次数的变量 private void Start() { Debug.Log("start 1"); //开启协程1 StartCoroutine(Test()); Debug.Log("start 2");