Search Unity

Start() being called before async Awake() finishes in another object

Discussion in 'Editor & General Support' started by CPlusSharp22, Jul 24, 2019.

  1. CPlusSharp22

    CPlusSharp22

    Joined:
    Dec 1, 2012
    Posts:
    111
    Hello!

    I have 2 game objects in a scene.
    One has code like this:

    Code (CSharp):
    1. private async void Awake()
    2. {
    3.     GameObject.DontDestroyOnLoad(this.gameObject);
    4.     Console.WriteLine("Starting awake");
    5.     await MyMethod();
    6.     Console.WriteLine("Done awake");
    7. }
    In another object, it's code is like this:

    Code (CSharp):
    1. async void Start()
    2. {
    3.     Console.WriteLine("Start happening");
    4.     // Do something
    5.     Console.WriteLine("Start done");
    6. }
    In the Editor, the output is:
    1. Starting awake
    2. Done awake
    3. Start happening
    4. Start done

    When I BUILD and run the executable, the output is:
    1. Starting awake
    2. Start happening
    3. Start done
    4. Done awake
    I thought Awake of all objects is guaranteed to be called before the Start of other objects. And it's peculiar to me this is happening only after I build.
     
    twobob likes this.
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Awake did get called first, but you're suspending Awake on line 5. Async tasks behave differently in the editor vs a build, such as when you async additive load a scene in editor it blocks until complete, but does not in a build. I haven't tried declaring Awake with async and suspending it like you're doing, but your reported results are exactly what I would expect.

    Start gets called before Update at the next frame. For your suspended Awake to finish before Start, that would require blocking the main thread so it does not move on to the next frame. But the point of an async suspend is the opposite of what you apparently want.