introduce
In Unity, Invoke
and InvokeRepeating
are two commonly used functions, which are used to execute a specific function after a certain time delay or repeatedly execute a specific function within a certain time interval. They are often used to handle scenarios such as timing tasks, animation triggering, and event scheduling.
Compared
parameter
Invoke
- function_name: The name of the function to delay execution.
- Delay Time: The amount of time (in seconds) to wait before delaying execution of the function.
InvokeRepeating
- Function Name: The name of the function to be executed repeatedly.
- Delay Time: The amount of time (in seconds) to wait before starting the repeated execution.
- Repeat Interval: The interval in seconds between repeated executions of the function.
Execution times
Invoke
Invoke
The function will only execute the deferred function call once.
InvokeRepeating
InvokeRepeating
The function will start to execute the function repeatedly after the delay time, and execute the function again at the specified repetition interval. Repeated execution can be stopped by calling CancelInvoke()
a function.
cancel execution
Invoke
Delayed execution CancelInvoke()
via a function can be canceled using a function.Invoke
InvokeRepeating
Repeated execution CancelInvoke()
through functions can be canceled using functions.InvokeRepeating
for example
Invoke
using UnityEngine;
public class ExampleClass : MonoBehaviour
{
void Start()
{
Invoke("DelayedFunction", 2f);
}
void DelayedFunction()
{
Debug.Log("This function is called after a 2-second delay.");
}
}
In the example above, DelayedFunction
the function will execute with a delay of 2 seconds after it is started.
InvokeRepeating
using UnityEngine;
public class ExampleClass : MonoBehaviour
{
void Start()
{
InvokeRepeating("RepeatedFunction", 2f, 3f);
}
void RepeatedFunction()
{
Debug.Log("This function is repeatedly called every 3 seconds after a 2-second delay.");
}
}
In the example above, RepeatedFunction
the function will execute with a delay of 2 seconds after startup, and repeat every 3 seconds thereafter.