提供了两种异步方式的调用
(1) coroutine(协程) 应该是untity对c#多线程的一种封装吧(内部不是很了解),调用的函数需标示IEnumerator迭代配合yield return xxx使用
yield标示着是否暂停迭代,yield return true;继续下面代码,否则将挂起.
(2)invoke 类似于as/js的setTimeout,指定延迟时间后执行一个方法,不同于coroutine,调用时不可加参数
InvokeInvokes the method methodName in time seconds.
在time秒调用methodName方法;简单说,根据时间调用指定方法名的方法
InvokeRepeatingInvokes the method methodName in time seconds.
在time秒调用methodName方法;简单说,每隔指定时间调用指定方法名的方法
CancelInvokeCancels all Invoke calls on this MonoBehaviour.
取消这个MonoBehaviour上的所有调用。
IsInvokingIs any invoke on methodName pending?
某指定函数是否在等候调用。
StartCoroutineStarts a coroutine.
开始协同程序。
StopCoroutineStops all coroutines named methodName running on this behaviour.
停止这个动作中名为methodName的所有协同程序
StopAllCoroutinesStops all coroutines running on this behaviour.
停止所有动作的协同程序
eg:
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Start() {
print("Starting " + Time.time);
StartCoroutine(WaitAndPrint(2.0F));
print("Before WaitAndPrint Finishes " + Time.time);
}
IEnumerator WaitAndPrint(float waitTime) {
yield return new WaitForSeconds(waitTime);
print("WaitAndPrint " + Time.time);
}
}
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
public Rigidbody projectile;
void LaunchProjectile() {
Rigidbody instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere * 5;
}
public void Awake() {
InvokeRepeating("LaunchProjectile", 2, 0.3F);
}
}