一.协程
协程是u3d提供的一种迭代器管理机制
void Start () {
print (0);
StartCoroutine (wait (3));
print (1);
}
IEnumerator wait(float s) {
print (2);
yield return new WaitForSeconds (s);
print (3);
}
二.协程实现的延时调动
using UnityEngine;
using System.Collections;
using System;
public class Delay {
public static IEnumerator run(Action action, float delaySeconds) {
yield return new WaitForSeconds(delaySeconds);
action();
}
}
三.Invoke的延时调用
Invoke类似于js的setTimeout,还有类似于setInterval的InvokeRepeating,但远不如js强大,
Invoke系列只能接受字符串形式的方法名,按名延时调用,例如:
int arg;
void Start() {
arg = 1;
Invoke ("doSth", 3);
}
void doSth() {
print (arg);
}
// => [3s later] 1
因为字符串形式不能传参,所以用了全局变量来传,语法很简洁,也没有让人迷惑的地方
特别注意:上面提到的2种延时调用失败的情况仍然存在
四.Time.time实现延时调用
比较笨的方法,但能够避免切换场景和销毁物体导致延时调用失效的问题,代码如下:
using UnityEngine;
using System.Collections;
using System;
public class Wait : MonoBehaviour {
static Action _action;
static float time;
static float delayTime;
// Use this for initialization
void Start () {
// 切换场景时不销毁该物体
DontDestroyOnLoad (gameObject);
reset ();
}
// Update is called once per frame
void Update () {
if (Time.time > time + delayTime) {
_action();
reset();
}
}
void reset() {
time = 0;
delayTime = int.MaxValue;
}
public static void runAfterSec(Action action, float s) {
_action = action;
time = Time.time;
delayTime = s;
}
}