If I add a GameObject with two components and add it to a scene the Awake, Start, and Update methods get called in this order:
- Components A B Awake
- Components A B Start
- Components A B Update
If I make this same GameObject into a prefab and create using Instantiate() I get this order:
- Components A B Awake
- Components A Start
- Components A Update
- Component B Start
- Component B Update
You cannot and should not depend on ordering of A and B for any individual method (Awake, Start, or Update).
It seems you can rely on Awake for A B getting called before any Start or Update calls for either A B independent of how the GameObject is created.
But you can only rely on Start getting called before Update gets called on that particular component, the Update method on another component that is part of the same GameObject may be called before all Components that make up a GameObject have had their Start method called.
This means that if you use Component B from Component A (or vice versa) you cannot be sure if the other component is fully initialized when you first use it in your Update method as the other component’s Start method may not have run. You can often work around this issue by moving initialization code from the Start method to the Awake method, but that defeats the benefits of the Start method. You can also “check” to see if a component has had its Start method called before using it the first time, but this also seems less than ideal.
Is there a good reason why Instantiate doesn’t call Start on all components in a particular game object before calling any Update method on any of the components that make up that game object? It seems like it would make initialization much simpler and consistent?
Am I going about this all wrong? How should I handle initialization code in Awake and Start when different components in the same GameObject reference each other?
Thanks!