Invoke — Unity
In the previous article, I wrote about Time in Unity.
This article will focus on the Invoke method in Unity.
The Invoke function allows the user to call events at a scheduled time.
There are 3 kinds of Invokes, Invoke, InvokeRepeating, and CancelInvoke.
A great use case for Invoke in Unity is to Spawn Game Objects.
Invoking->
A simple Invoke call can look like this…
Here, I want to setup the Invoke function, that calls the method Spawn Target, and given a time to process the event call.
The Invoke function, will take in or call the function to execute, followed by a time.
With the Spawn Target function, I’ll set the spawn position as a new Vector 3 for the Game Object that’s spawned with the Invoke function call.
And now, I can test the Invoke function.
Get Zac Bogner’s stories in your inbox
Join Medium for free to get updates from this writer.
After the time specified in code, invoke function will call the spawn target.
Next, will be Invoke Repeating.
Invoke Repeating->
Invoke repeating responds by a time and a repeating amount.
I’ll setup another function, that will spawn the spawn object randomly on the x and z axis using a Random Range parameter.
And now, here’s a demonstration for Invoke Repeating.
The final Invoke function is Cancel Invoke.
Cancel Invoke->
Cancel Invoke is a simple function, where an Invoke function can be stopped by using the Cancel Invoke call.
I’ll create a statement where I check if the spawn time is > 10, if it is and I press the space key, the Cancel Invoke function will fire, stopping the active invoke in cue.
This will cancel the invoke functions active in the script.
And that’s all for Invoke in Unity.
Stay tuned for more.
Thanks,
Zac B.










