When do you use StartCoroutine and when Invoke? 3miOo g EeYXt Ff 50 Uu Nnw X Bth o Ph Ip su W YyZzt
I am confused. Both seem to do the same thing: Delay a method.
Both Invoke and StartCoroutine allow you to call a method by name (string).
StartCoroutine("functioncalls", 2f);
StartCoroutine(functioncalls());
Invoke:
void Call()
{
Invoke("FunctionCall",2f);
}
void FunctionCall()
{
Debug.Log("this function run");
}
StartCoroutine:
void Call()
{
StartCoroutine(functioncalls());
}
IEnumerator functioncalls()
{
yield return new WaitForSeconds(2f);
Debug.Log("this function run");
}
Both do the same thing, or not?
What exactly is the difference between Invoke and StartCouroutine? In which situation would I use one and when the other?
1 Answer
Invoke is useful if you want to do something one time only.
A coroutine is able to pause, let the game continue running, and then do something else later. This makes them useful for processes which run over time. Also, you can pass arguments to a coroutine. The Invoke method does not allow that.
Example of a coroutine which implements a countdown:
IEnumerator Countdown(int seconds)
{
while (seconds > 0) {
Debug.Log(seconds);
seconds--;
yield return new WaitForSeconds(1f);
}
Debug.Log("Go!);
}
You can now use this function to do a countdown of arbitrary length. For example, if you want to start a 10 second countdown, you would call
StartCoroutine(Countdown(10));
However, if you want to do something in 10 seconds without having a visible countdown leading up to the event, then it would be easier to use Invoke:
void Go()
{
Debug.Log("Go!);
}
...
Invoke("Go", 10f);
-
\\$\\begingroup\\$ exactly what i need . The same coroutine won't be called multiple times in an overlapping fashion?? it is true or not \\$\\endgroup\\$ – rahul patil 8 hours ago
-
\\$\\begingroup\\$ @rahulpatil You can run multiple overlapping instances of the same coroutine at the same time in parallel if you want to. \\$\\endgroup\\$ – Philipp 8 hours ago
-
\\$\\begingroup\\$ Another useful tidbit is that you can control when in the frame the coroutine resumes, aligning it with the FixedUpdate loop or end of frame. You can even tell it to wait for a download to finish, or for another coroutine to end, or any other condition of your choice. \\$\\endgroup\\$ – DMGregory♦ 7 hours ago