Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Coroutine, setactive and frame execution order

Discussion in 'Editor & General Support' started by Arnleif, Jan 29, 2013.

  1. Arnleif

    Arnleif

    Joined:
    Sep 27, 2012
    Posts:
    10
    Hi, I encountered a problem when I tried to activate an inactive gameobject ( and it's childs) from a coroutine.
    It turned out that the order of execution was somewhat different than normal.
    The problem was (almost*) fixed by using
    yield return new WaitForEndOfFrame();
    instead of
    yield return null;

    I've now learned that "yield return null;" runs after the Update loop so the order of execution that you'll see below make some sense, but.
    My question is, is this a bug? Or do I have to take into account where in the frame I call setactive( true ) on a gameobject?



    This was my test. (Unity 4.0.0f7)
    1 inactive gameobject named "test" and it's child "testNormal"

    ++test (1 script) ( gameobject is inactive from start )
    +- testNormal (2 scripts)
    Code (csharp):
    1.  
    2.     IEnumerator Starter()
    3.     {
    4.         yield return null;
    5. //      yield return new WaitForEndOfFrame();   // This works fine.
    6.         testObj.SetActive( true );
    7.     }


    My 2 scripts output in execution order. The added N is from the second script on "testnormal" so I could check if components on the same gameobject behaved odd also.

    "testnormal" also has an mechanim animator, as it was part of my original problem.
    You'll see two abnormalities below.
    1) OnAnimatorMove is called before start
    2) The first lateupdates are interleaving the Start calls.


    Output:

    awakeN testNormal
    awake testNormal
    awake test

    OnAnimatorMove testNormal frame: 0
    OnAnimatorMoveN testNormal frame: 0

    startN testNormal
    LateUpdateN testNormal lateframe: 0

    start testNormal
    LateUpdate testNormal lateframe: 0

    start test
    LateUpdate test lateframe: 0

    (From here on things run normal)

    FixedUpdate testNormal fixedFrame: 0-15
    FixedUpdate testNormal fixedFrame: 0-15
    FixedUpdate test fixedFrame: 0-15

    UpdateN testNormal frame: 0
    Update testNormal frame: 0
    Update test frame: 0

    OnAnimatorMove testNormal frame: 1
    OnAnimatorMoveN testNormal frame: 1

    LateUpdateN testNormal lateframe: 1
    LateUpdate testNormal lateframe: 1
    LateUpdate test lateframe: 1

    FixedUpdate testNormal fixedFrame: 16-22
    FixedUpdate testNormal fixedFrame: 16-22
    FixedUpdate test fixedFrame: 16-22

    etc.


    (* The reason I said 'almost' was because after using WaitForEndOfFrame, I did still get into some trouble in some case. I did not bother to investigate that case, and moved some of the code out of the coroutine. )