1.Invoke (string methodname,float time)
Call the MethodName function at a certain 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() {
Invoke(
"LaunchProjectile"
,
2
);
}
}
2.InvokeRepeating (String methodname,float time,float repeatrate)
Call the MethodName function every once in a while
Invokes the method MethodName in time seconds.
Call the MethodName method in time seconds; The method that specifies the method name according to the timing
After the first invocation repeats calling that function every repeatrate seconds.
It is called once every repeatrate time from the first call.
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);
//2秒后,没0.3f调用一次
}
}
3.CancelInvoke (String methodName)
Cancel all calls in this script
Cancels all Invoke calls in this monobehaviour.
Cancels all calls on this monobehaviour.
public
class
example : MonoBehaviour {
public
Rigidbody projectile;
void
Update() {
if
(Input.GetButton(
"Fire1"
))
CancelInvoke();
}
void
LaunchProjectile() {
instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere *
5
;
}
public
void
Awake() {
InvokeRepeating(
"LaunchProjectile"
,
2
,
0
.3F);
}
}
function LaunchProjectile () {
instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere *
5
;
}
4. (bool) isinvoking (String methodName)
using UnityEngine;
using System.Collections;
public
class
example : MonoBehaviour {
public
Rigidbody projectile;
void
Update() {
if
(Input.GetKeyDown(KeyCode.Space) && !IsInvoking(
"LaunchProjectile"
))
//如果这个方法不在调用并且等待了2秒
Invoke(
"LaunchProjectile"
,
2
);
}
void
LaunchProjectile() {
Rigidbody instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere *
5
;
}
}
Unity's timed call