Hello, I am just trying to better understand the execution order. I am aware of the “Execution Order” document from Unity, but this part is a bit ambiguous to me.
When I call Instantiate and I generate an object into the scene, is that GameObjects “Start()” function called in the same frame still, or will it wait until the next frame to execute?
What about the first time “Update()” gets called? Does Start() execute, then later Update is executed within the same frame still? Or does Start() execute, then on the next frame Update() is called for the first time?
Thanks and any help on this is greatly appreciated!
If you seem to be early enough in the overarching player loop, when you Instantiate a game object, Awake, OnEnable, and Start all get called before the next frame.
If you’re late enough in the player loop, it gets deferred until the next frame. Though in most cases, I believe, you can rely on it happening immediately. But do some testing on your end to be sure.
I forget too, and I think it may have subtly changed over the decade or more I’ve used Unity.
F’rinstance, at one point I remember experimenting and finding that ALL active MonoBehaviours appear to be gathered into some kind of list to have their Start() and Update() called all in the same frame.
Once that gather happens, nobody else gets Start/Update in this frame.
The trick is, I’m not sure where in the timing diagram that happens.
And for all we know, that point in the timing diagram MIGHT have changed! It’s not specified after all.
It’s always best to be explicit and inoculate yourself against future engine changes.
I think it is not guaranteed that Start()/Update() is called on the same frame as Instantiate()/SetActive().
A common case is where you SetActive() a GameObject on a UI button click. You can’t rely on the assumption that its Update will be called on the same frame as the button click event is emitted.
In fact, in my experience, it has always been the case that Update is deferred to the next frame. This is problematic because the GameObject might have a renderer whose state is configured in a scripted Update(). This can cause the renderer to display a bad state for a single frame.
This can be mitigated by either:
Forcing an update with 0 deltaTime in the script’s OnEnable().
Can you confirm this under which circumstances this occurs? Did you verify this with Time.frameCount and not confuse it with perhaps multiple objects being instantiated?
Though Start happening a frame early is hardly ‘worst case’. If anything, having the initialisation happening immediately is better for avoiding race conditions.
Also what does the render pipeline have to do with this?