- Home /
Is there a way to find out when a coroutine is done executing?
I do realize that I can just call my next function at the end of the coroutine or have a boolean to flag its execution.
But calling another function gets tricky when the code is complex and the function to be called depends on the lines executed in the coroutine itself.
Also when I have multiple coroutines running simultaneously.. I'll need multiple boolean flags which could get messy.
So is there any other way to know if a coroutine is completed?
$$anonymous$$aybe check the answers right here, you might find something you can use: https://forum.unity.com/threads/check-if-coroutine-is-finished.509036/
Answer by spilat12 · Jun 04, 2018 at 05:05 PM
To be honest, I did not know the precise answer to your question. However, while looking through forums, I found this. Real gold! This is basically an interface for Unity coroutines, which allows to pause, stop and check if it it's running.
In current times I prefer a solution that is also compatible with async/await.
Answer by ShadyProductions · Jun 04, 2018 at 01:25 PM
Here is an example I use so players cannot input while the story is advancing. For example:
private IEnumerator advanceStoryDelayRoutine;
IEnumerator AdvanceStoryDelayRoutine()
{
yield return new WaitForSeconds(3.5f);
advanceStoryDelayRoutine = null;
}
When using it
//this check is necessary for the first time or StopCoroutine will stop to nothing, resulting in a run time error
if(advanceStoryDelayRoutine != null)
{
StopCoroutine(advanceStoryDelayRoutine);
}
advanceStoryDelayRoutine = AdvanceStoryDelayRoutine();
StartCoroutine(advanceStoryDelayRoutine);
And then the input code can check against this variable
if(advanceStoryDelayRoutine != null)
{
//still hasn't finished yet
}
Forgive me if I'm wrong.. But isn't this just another way of flagging? I was looking for something of a listener.. like
IEnumerator cutScene()
{
yield return new waitForSeconds(20);
}
whenDone("cutScene")
{
resumeInput();
}
PS: By listener I mean something that constantly checks if a coroutine is done.
Answer by Ranger-Ori · May 03, 2021 at 04:20 AM
I use Callback:
public IEnumerator CoroutineFunction(..., Action<int> callback)
{
yield return new waitForSeconds(<number>);
callback(<number>)
}
For instance:
public IEnumerator CoroutineFunction(Action<int> callback)
{
yield return new waitForSeconds(20);
callback(1)
}
StartCoroutine(CoroutineFunction(result =>
{
myVariable = result;
})
);
My lambda function would initiate when the callback would be performed.
Your answer
Follow this Question
Related Questions
Running a coroutine without StartCoroutine 1 Answer
NullReferenceException in StartCoroutine 1 Answer
C# - Coroutines for Abilities 1 Answer
How to wait for a co routine to finish when calling from a method 1 Answer
move inside a coroutine 2 Answers