InvokeScript using UnityEngine; using System.Collections; public class InvokeScript : MonoBehaviour
{ public GameObject target;
void Start(){
Invoke ("SpawnObject", 2);
} void SpawnObject(){
Instantiate(target, new Vector3(0, 2, 0), Quaternion.identity);
}
}
InvokeRepeating using UnityEngine; using System.Collections; public class InvokeRepeating : MonoBehaviour
{ public GameObject target;
void Start(){
InvokeRepeating("SpawnObject", 2, 1);
} void SpawnObject(){ float x = Random.Range(-2.0f, 2.0f); float z = Random.Range(-2.0f, 2.0f);
Instantiate(target, new Vector3(x, 2, z), Quaternion.identity);
}
}
Invoke() 方法是 Unity3D 的一种委托机制 如: Invoke("Test", 5); 它的意思是:5 秒之后调用 Test() 方法; 使用 Invoke() 方法需要注意 3点: 1 :它应该在 脚本的生命周期里的(Start、Update、OnGUI、FixedUpdate、LateUpdate)中被调用; 2:Invoke(); 不能接受含有参数的方法; 3:在 Time.ScaleTime = 0; 时, Invoke() 无效,因为它不会被调用到 Invoke() 也支持重复调用:InvokeRepeating("Test", 2 , 3); 这个方法的意思是指:2 秒后调用 Test() 方法,并且之后每隔 3 秒调用一次 Test() 方法 还有两个重要的方法: IsInvoking:用来判断某方法是否被延时,即将执行 CancelInvoke:取消该脚本上的所有延时方法
|