版本: 2018.2
原文: Execution Order of Event Functions
Script Lifecycle Flowchart 脚本生命周期流程图
The following diagram summarises the ordering and repetition of event functions during a script’s lifetime.
In Unity scripting, there are a number of event functions that get executed in a predetermined order as a script executes. This execution order is described below:
Unity框架有一个复杂的游戏循环
First Scene Load 第一次场景加载
These functions get called when a scene starts (once for each object in the scene).
-
Awake:
- This function is always called before any Start functions and also just after a prefab is instantiated. (If a GameObject is inactive during start up Awake is not called until it is made active.)
- 调用时机:
- 在prefab被实例化之后调用(todo)
- 在调用
Start
之前调用
- 注意:
- 如果GameObject在游戏启动时处于非活动状态,则不会调用
Awake
, 直到它被激活才会调用Awake
- 不切换场景的情况下,
Awake
只会在首次激活时调用, (只调用一次) - 在所有对象都初始化之后, 才调用
Awake
, 所以可以安全地与其他对象交互, 或使用例如GameObject.FindWithTag
来查找对象 - 在Unity中, 使用
Awake
而不是构造函数来进行初始化,因为组件的序列化状态在构造时未定义。Awake
仅被调用一次,就像构造函数一样。 Awake
不能作为协程- 任何
Start
调用之前, 总是先调用Awake
- 如果GameObject在游戏启动时处于非活动状态,则不会调用
-
OnEnable:
- (only called if the Object is active): This function is called just after the object is enabled. This happens when a MonoBehaviour instance is created, such as when a level is loaded or a GameObject with the script component is instantiated.
- 调用时机
- MonoBehaviour实例被创建之后(例如关卡加载时, 或GameObject的脚本被实例化)
- 对象启用后立即调用此函数
- 注意:
- 仅在Object处于激活状态时调用 (激活对象的函数有:
GameObject.SetActive(true)
) - 每次启动时都会调用!(启动对象的函数有
object.enable = true
)
- 仅在Object处于激活状态时调用 (激活对象的函数有:
-
OnLevelWasLoaded:
- This function is executed to inform the game that a new level has been loaded.
- 调用时机:
- 当一个新的关卡被加载完毕的时候
- 类似功能的API
- SceneManager.sceneLoaded: 添加一个委托, 在加载场景完毕时会自动调用这个委托