多语言展示
当前在线:1315今日阅读:61今日分享:18

Unity中MonoBehaviour的生命周期注意点

在Unity中,弄清楚整个脚本的生命周期是非常重要的,以下的一些注意点可以帮助你更好的了解Unity的生命周期
方法/步骤
1

当脚本所依附gameObject的父级gameObject被Inactive时(或active),该gameObject的周期还是会被触发的,例如OnEnable、OnDisable

2

不同的gameObject间的脚本周期执行顺序是随机的,但会将screen上所有gameObject同一阶段执行完才开始下一个阶段,例如,screen上有5个gameObject,会先把5个gameObject的Awake执行完,再开始执行他们的Start。(注意,Awake是紧接着OnEnable的,可以看成是一个阶段)

3

假如在Awake处调用gameObject.SetActive(false),会进入到OnDisable,其他阶段不会执行

4

请注意Start()Api中最后一段“Where objects are instantiated during gameplay, their Awake function will naturally be called after the Start functions of scene objects have already completed.”,在unity的论坛中找到了相关答案。It's saying that anything in the scene to start with will have it's Awake and then it's Start function called. If you instantiate a prefab after the scene has started (or during some scene item's Start or Awake) and then it will have its Awake called, followed by its Start, but that how that relates to the Awake and Start of any other item is dependent on the order in which things are created.So while Awake happens for all objects in a scene before any of them get Start - if you make things later then many existing Awake and Start functions will have already completed.例如,screen上有5个gameObject----A、B、C、D、E,现在Unity为我们随机到的执行顺序是C、E、A、D、B。假如此时我们在A中的Start中Instantiate一个新的gameObejct----F,这个F的Awake是会跟着A的Start后执行的。具体这个是要看A的执行顺序。

推荐信息