一.协程
    协程是u3d提供的一种迭代器管理机制

    1. void Start () {
    2. print (0);
    3. StartCoroutine (wait (3));
    4. print (1);
    5. }
    6. IEnumerator wait(float s) {
    7. print (2);
    8. yield return new WaitForSeconds (s);
    9. print (3);
    10. }

    二.协程实现的延时调动

    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. public class Delay {
    5. public static IEnumerator run(Action action, float delaySeconds) {
    6. yield return new WaitForSeconds(delaySeconds);
    7. action();
    8. }
    9. }

    三.Invoke的延时调用
    Invoke类似于js的setTimeout,还有类似于setInterval的InvokeRepeating,但远不如js强大,
    Invoke系列只能接受字符串形式的方法名,按名延时调用,例如:

    1. int arg;
    2. void Start() {
    3. arg = 1;
    4. Invoke ("doSth", 3);
    5. }
    6. void doSth() {
    7. print (arg);
    8. }
    9. // => [3s later] 1

    因为字符串形式不能传参,所以用了全局变量来传,语法很简洁,也没有让人迷惑的地方
    特别注意:上面提到的2种延时调用失败的情况仍然存在
    四.Time.time实现延时调用
    比较笨的方法,但能够避免切换场景和销毁物体导致延时调用失效的问题,代码如下:

    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. public class Wait : MonoBehaviour {
    5. static Action _action;
    6. static float time;
    7. static float delayTime;
    8. // Use this for initialization
    9. void Start () {
    10. // 切换场景时不销毁该物体
    11. DontDestroyOnLoad (gameObject);
    12. reset ();
    13. }
    14. // Update is called once per frame
    15. void Update () {
    16. if (Time.time > time + delayTime) {
    17. _action();
    18. reset();
    19. }
    20. }
    21. void reset() {
    22. time = 0;
    23. delayTime = int.MaxValue;
    24. }
    25. public static void runAfterSec(Action action, float s) {
    26. _action = action;
    27. time = Time.time;
    28. delayTime = s;
    29. }
    30. }