Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Do I understand this right about yield and coroutines?

Discussion in 'Scripting' started by stefan_s_from_h, Apr 29, 2022.

  1. stefan_s_from_h

    stefan_s_from_h

    Joined:
    Nov 26, 2017
    Posts:
    72
    yield can only be used inside a method with IEnumerator return type. If I call another method inside this IEnumerator declared method and decide I want to start a synchronous coroutine via
    yield return StartCoroutine(SomeExampleMethod());
    I'm out of luck, because yield isn't allowed there.

    IEnumerator A() { … }
    B() { … }
    IEnumerator C() { … }

    A() calls B() and B() decides that it wants to start C(), but synchronous. Not possible. Instead B() needs to communicate to A() that it needs to start C().

    Do I understand this correctly?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,749
    Yes, a function can only execute and return.

    If you wanna do that, just make B() into a coroutine too.
     
  3. stefan_s_from_h

    stefan_s_from_h

    Joined:
    Nov 26, 2017
    Posts:
    72
    I wanted to avoid that and in doing so would end up with a complicated mess.

    Thanks to your answer I took a step back to looked at it again.

    In the end it's an API and B() is supplied by the user. Over 99% of all cases there's no need to call C() at all. For the <1% of cases I will make it that the user supplies a coroutine and calls C() the right way.

    Easy usability for over 99% of the time and a little bit tricky for the rest. Should be good UX.
     
    Kurt-Dekker likes this.