- Home /
Handling components instancing order
I'm trying to implement the idea of pluggable & decoupled components in my GameManager, instead of having one class do everything. In that perspective, I have several scripts on an empty gameobject: GameManager, UIManager, SpawnManager, ObjectPool, EventManager and Music Manager. Most of the time this works fine, but every once in a while the game won't start and throw a dozen of null reference errors. This is due to the fact that most of the above scripts subscribe to the EventManager (a singleton) inside OnEnable, and sometimes (or so it seems) they can't find it because it hasn't been instanced yet. I've trying starting with all components disabled (except for GameManager) and hoping that the GameManager could enable them one by one in Awake. But this is still not a guarantee that the EventManager will have instanced before I enabled them. How is this issue solved most of the time (it seems like a very basic problem)? I thought OnEnabled got called after Awake. Thanks.
Answer by pako · Feb 03, 2018 at 08:36 PM
Try setting the Script Execution Order:
https://docs.unity3d.com/Manual/class-MonoManager.html
BTW, I noticed that in the above document, it says that OnEnable is called before Awake. This is in contradiction with:
https://docs.unity3d.com/Manual/ExecutionOrder.html
Additionally, all my tests have shown that Awake always gets called before OnEnable in the same script. However, OnEnable is called directly after Awake in the same script, which means that in different scripts, Awake will be called after OnEnable of the previous script, e.g. for 3 scripts, the execution order is:
Script 1: Awake, OnEnable
Script 2: Awake, OnEnable
Script 3: Awake, OnEnable
i.e. Awake of Script 3 will be called after OnEnable of Script 2, etc.
Your answer
