Home > Back-end >  Unity - How can I throw except out in coroutine "yield return"
Unity - How can I throw except out in coroutine "yield return"

Time:10-21

IEnumerator CoTest()
{
  yield return CoTest2();

  Debug.Log("Done");
}

If CoTest2 had error , I want to stop exactly line I called ( yield return CoTest2(); ) before Debug.Log("Done");

Is there any way to do this ? or better way

CodePudding user response:

Just surround your code with a "try/catch" block (see "Exception Handling" for further details). The further execution of your code will be immediately stopped when an exception occurs in CoTest2 and you will fall through to the catch block.

IEnumerator CoTest()
{
    try
    {
        yield return CoTest2();

        Debug.Log("Done");
    }
    catch( Exception ex )
    {
        // Handle the exception here
    }
}
  • Related