- Home /
How to start a Method after Coroutine has finished
Hello,
i have a problem with my Program. The program needs to run several methods and has one recursive method which uses the WaitForSeconds method. Right now the ThirdTask() gets immediately called after SecondTask(). But to run correct the SecondTask must be completed before the ThirdTask(). Has someone an idea how i can solve this problem?
Thank you for your help.
public void MyProgram ()
{
FirstTask ();
SecondTask (int one, int two);
ThirdTask ();
}
public void SecondTask(int one, int two)
{
//Do some stuff first
StartCoroutine(TheCoroutine (int one, int two));
}
private IEnumerator TheCoroutine( int one, int two)
{
case 0:
yield return new WaitForSeconds(0.01f);
yield return StartCoroutine(TheCoroutine (int one, int two));
break;
case 1:
yield return new WaitForSeconds(0.01f);
yield return StartCoroutine(TheCoroutine (int one, int two));
break;
}
Answer by cjdev · Aug 23, 2015 at 02:39 AM
You could turn your second task into a coroutine as well so that it can yield and wait for TheCoroutine to finish. After that you can place the call to ThirdTask at the end of SecondTask rather than in the main program so that it is delayed like this:
public void MyProgram ()
{
FirstTask();
StartCoroutine(SecondTask(one, two));
}
public IEnumerator SecondTask(int one, int two)
{
//Do some stuff first
yield return StartCoroutine(TheCoroutine(one, two));
ThirdTask();
}
Answer by AtM5 · Aug 24, 2015 at 11:51 AM
An ugly way is to put your ThirdTask() at the end of the coroutine from SecondTask()
private IEnumerator TheCoroutine( int one, int two)
{
case 0:
yield return new WaitForSeconds(0.01f);
yield return StartCoroutine(TheCoroutine (int one, int two));
break;
case 1:
yield return new WaitForSeconds(0.01f);
yield return StartCoroutine(TheCoroutine (int one, int two));
break;
}
ThirdTask()
yield return null;
There may be another option though :)
Answer by MFKJ · Apr 17, 2020 at 12:57 PM
You can pass Action parameter to your coroutine function here, is the sample code.
public class CoroutineDemo : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
StartCoroutine(CoroutineDemonstration(MethodCallAfterCoroutineFinshed));
}
IEnumerator CoroutineDemonstration(Action action)
{
Debug.Log("Coroutine Started");
yield return new WaitForSeconds(2);
Debug.Log("Corouine Ended.");
action();
}
void MethodCallAfterCoroutineFinshed()
{
Debug.Log("Corouine Ended After.");
}
}
Here is the 3-minute explantion.
Your answer
Follow this Question
Related Questions
Load Level when dead for 1 second 2 Answers
Rotate an object using Quaternion.RotateTowards() inside a Coroutine? 1 Answer
Can't get past WaitForSeconds in my coroutine 1 Answer
Coroutine doesn't work when called from another method. 3 Answers
Coroutine not running after yield return new WaitForSeconds 3 Answers