Search Unity

Instant coroutine ?

Discussion in 'Scripting' started by Bulwark-Studios, Aug 25, 2017.

  1. Bulwark-Studios

    Bulwark-Studios

    Joined:
    Sep 20, 2013
    Posts:
    18
    Hello!

    I try to start an empty coroutine for a design reason. I can't find a way to execute that coroutine without wait until the next frame to execute the next part of my code.

    There is a sample code (the Execute() method is started with the StartCoroutine() method) :

    Code (CSharp):
    1. public override IEnumerator Execute() {
    2.  
    3.             Debug.Log("test2");
    4.  
    5.             // Node controllable
    6.             INodeControllable nodeControllable = item.GetComponent<INodeControllable>();
    7.             if (nodeControllable != null) {
    8.                 yield return StartCoroutine(Execute(nodeControllable));
    9.             }
    10.  
    11.             Debug.Log("test3");
    12.  
    13. }
    14.  
    15. protected virtual IEnumerator Execute(INodeControllable node) {
    16.             yield break;
    17. }
    What I want is when a class doesn't override the Execute method, "test2" and "test3" are logs in the same frame.

    Is there something i'm missing here ?

    Thanks!
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    You'll need to manually run your inner coroutine:

    Code (csharp):
    1. if (nodeControllable != null) {
    2.     var innerRoutine = Execute(nodeControllable());
    3.     while(innerRotuine.MoveNext())
    4.         yield return innerRotuine.Current;
    5. }
    An IEnumerator that hits yield break on it's first MoveNext will return false, so your while-loop will never run and nothing will be yielded by it.
     
    IgorAherne, Silvarc and a436t4ataf like this.
  3. Bulwark-Studios

    Bulwark-Studios

    Joined:
    Sep 20, 2013
    Posts:
    18
    Hi Baste!

    Thanks for the tip it's working really great.