[SOLVED] AppStates initialization order

Good day,
Recently I have noticed a strange behavior of AppState's methods execution order.
I adds one app state inside initialize method of another. When you create AppState's instance initialize method executed the first and onEnable after it. I am adding second AppState in initialize method of first and expect the following action order -

  • First app state initialize method executed first
  • Creating second app state instance in constructor of first
  • Second app state initialize
  • onEnable method of second app state must be executed after it
  • onEnable method of first app state must be executed at the end

I have noticed that onEnable method of first app state executed before the initialize method of the second and in fact I gets the next order of methods execution:

  • First app state initialize
  • First app state onEnable
  • Second app state initialize
  • Second app state onEnable

Why I am getting this order if Second app state added inside initialize method of the First app state?

Just taking a quick look at the code… it looks like attaching states is multithreaded which is why the order is different.

I don’t think it’s multithreaded - I think it’s synchronized.

The order is correct so far as I understand.

  • First appstate is added. On the next tick it will be initialized and enabled.
  • Second appstate is added during first initialize. In the next tick it will initialize and enable.

So i expect:

  • first appstate initialize and enable.
  • second appstate created in first initialize and enable.

Which is what is happening.

To me this is expected behavior.

Sorry, that’s what I meant by multithreaded :slight_smile:

1 Like

If I create second app state inside first, initialize and onEnable methods of first app state always will be executed before these methods of second app state?

yes because when you add an appstate, it doesn’t get initialized until the next frame/tick of the loop. But the first has been added and is initializing, after initialize it will call onEnable. Then in the next tick/frame the second will be added and go through the same procedure.

They are executed in order of addition. So if you add both one after another, they will execute one after another.


That will init stateOne then init stateTwo. then onEnable stateOne, then onEnable stateTwo.


And note: not always but quite often, when initialization order of app states is giving you worries it’s a sign that the app states have a design issue.

1 Like