What are Unity Invoke, InvokeRepeating and CancelInvoke?
What are Unity Invoke, InvokeRepeating and CancelInvoke?
In Unity, these are the commands that enable us to call functions repeatedly without creating an enumerator or to call them after a certain amount of time, i.e., with a delay. Let’s take a closer look at these commands in detail.
What is Invoke?
Invoke is a command that enables a function to run after a specified amount of time.
If we look at the parameters of the Invoke command:
Invoke("function name", time to call);
Example:
private void Start(){
Invoke("deneme", 2f);
}
private void deneme(){
debug.log("Function that runs after 2 seconds");
}
What is InvokeRepeating?
InvokeRepeating is a command that allows a function to run at specified intervals.
If we look at the parameters of the InvokeRepeating command:
InvokeRepeating("function name", first run time, repeat interval);
Example:
private void Start(){
InvokeRepeating("deneme", 3f, 1f);
}
private void deneme(){
debug.log("Function that is called for the first time 3 seconds after the program starts and runs at 2-second intervals");
}
What is CancelInvoke?
CancelInvoke is a command that ensures the command repeatedly called with InvokeRepeating is no longer called. In other words, it allows us to cancel the Repeating event.
If we look at the parameters of the CancelInvoke command:
CancelInvoke("function name");
Example:
int i = 0;
private void Start(){
InvokeRepeating("deneme", 3f, 1f);
}
private void deneme(){
i++;
if(i <= 5){
debug.log("Function that is called for the first time 3 seconds after the program starts and runs at 2-second intervals stops after the 5th run.");
}
else{
CancelInvoke("deneme");
}
}


Yorum Gönder