GameObject update order in Unity

2020-06-23 06:34发布

问题:

The Unity Manual describes the order in which the Script functions are called. However, I was wondering if there were any rules regarding the order in which the GameObjects themselves are considered in Unity.

GameObjects are basically the nodes of Unity's scene graph and (assuming the scene itself was the root node) they form a tree. I was wondering if that tree structure imposed any rules on the order in which GameObjects are considered.

As already mentioned, the manual describes that Awake() is always called before Start() which is always called before the first call to Update() and so on. However, these relations in time are (mostly) given in scope of a single script on a single GameObject. I want to know if there is also a rule stating the order in which Start() (or any other method) is called on all the GameObjects in the scene.

Specifically I wanted to know:

  1. Are parents always considered before their children are?
  2. Are siblings considered in the same order they are displayed in the scene graph?
  3. Is Script Execution Order enforced only in scope of a single GameObject, or does it consider all GameObjects?

回答1:

I built a small test project in Unity which basically consists of a 3x3x3 tree of GameObjects, each having 3 scripts.

I found the following answers:

  1. No. Some GameObjects can be considered before their parents are, while some parents can be considered before their children are. And this order can change when reloading the scene or manipulating the scene graph.
  2. No. Siblings can be updated in any order. This order can change when reloading the scene or manipulating the scene graph.
  3. It is enforced over all GameObjects in the scene. If SEO sets script A to be executed before script B, then all instances of script A will be considered before any instance of script B is. Meaning, all instances of A call their Awake() before any B call their Awake(), then all instances of A call their Start() before any instance of B call their Start() and so on.