[注解]Execution Order of Event Functions: Unity生命周期及常见问题

本文详细介绍了Unity中脚本的生命周期,包括Awake、Start、OnEnable、OnDisable、OnDestroy等函数的调用时机。特别讨论了Awake与Start的区别,对象激活与启用的差异,以及在游戏暂停、渲染、协同程序阶段的相关函数。此外,还提到了在编辑器环境下的特殊行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版本: 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.

img

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
  • 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 )
  • OnLevelWasLoaded:

    • This function is executed to inform the game that a new level has been loaded.
    • 调用时机:
      • 当一个新的关卡被加载完毕的时候
    • 类似功能的API
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值