- Home /
OnEnable called before Awake
I had some weird behavior in my code which took some time to find the problem. I have two scripts, one works with the data OnEnable, other on Awake, i added debugs to see execution order.
public class Player : MonoBehaviour {
private void OnEnable(){
Debug.Log ("registering events");
}
}
public class InputManager : MonoBehaviour{
private void Awake(){
Debug.Log("awake");
}
}
Console
How is this possible? Docs clearly show that OnEnable is called after Awake. All gameobjects components live on are active and components enabled.
Project came from other dev, is it possible he changed execution order (not sure if thats possible). Ive never seen anything like this.
Edit:
I just created two empty scripts A and B with only this code in each of them, each on its own dummy gameobject, execution order is correct for them. I even attached these components to same gameObjects, execution order is still correct, but reversed on old scripts!
Use Start() if possible - it will executed after all scene objects Awakes and OnEnables have been called.
Answer by Garazbolg · Oct 14, 2015 at 08:31 AM
Actually Unity doesn't do all awake() and then all OnEnable(). For each script that it loads he does Awake() OnEnable and move on to the next script. So your problem is that Unity load Player first and then InputManager.
But there is a way to fix this built in Unity : The script Execution Order that you can find under Edit/ProjectSettings/Script Execution Order ( http://docs.unity3d.com/Manual/class-ScriptExecution.html ).
Hope that helped ya figure it out.
Answer by jdelcin · Feb 11, 2018 at 05:55 PM
The order in which the scripts are placed in the "Hierarchy" affects their execution order as well. Meaning moving the object with script attach up on the hierarchy in the editor will determine what executes before and after it.
I know it's an old post, but could you please share a link with information you wrote?
I just confirmed this in my tests. You can create a clean empty scene and test this yourself with some debug scripts.
If this behavior isn't documented it can be changed at some point and break the project.
Do not rely on this! Script execution order can be different even between editor and its builded app. Design your app as if it is random.
Your answer
Follow this Question
Related Questions
OnEnable not called after all Awake and not all OnDisable before OnDestroy? 1 Answer
Does the access modifier of Start(), Awake(), OnEnable() make a difference to Unity? 3 Answers
OnEnable and Awake depreciated? 1 Answer
Reliable way to detect when the game starts playing on a ScriptableObject? 1 Answer