Cocos Creator, like Vue, has its own lifecycle callback, from game loading to game ending. Let’s introduce it.

Lifecycle callback functions include the following:

  • onLoad
  • start
  • update
  • lateUpdate
  • onDestroy
  • onEnable
  • onDisable
onLoad

The onLoad callback is first activated on the node. The onLoad phase ensures that you can retrieve the other nodes in the scene, as well as the resource data associated with the nodes. OnLoad is always executed before any start method calls, which can be used to arrange the script’s initialization order. We usually do some initialization in the onLoad phase.

start

The start callback is fired before the component is first activated, that is, before the first update is performed. Start is usually used to initialize data that needs to be modified frequently and may change during updates.

update

A key aspect of game development is updating the behavior, state, and orientation of objects before each frame is rendered. These update operations are usually placed in the UPDATE callback.

lateUpdate

Update is performed before all animation updates, but if we want to do something extra after dynamic effects (animation, particle, physics, etc.) are updated, or if we want to do something else after all component updates have been performed, we need to use the lateUpdate callback.

onEnable

The onEnable callback is activated when the enabled property of the component changes from False to true, or when the active property of the node on which it resides changes from False to true. If the node is created for the first time and enabled is true, it will be called after onLoad and before start.

onDisable

The onDisable callback is activated when the enabled property of the component changes from True to false, or when the active property of the node on which it resides changes from True to false.

onDestroy

The onDestroy callback is called when a component or node calls Destroy (), and the component is uniformly recycled when the frame ends. When onLoad and onDestroy are declared together, they will always be called in pairs. That is, from the time a component is initialized to the time it is destroyed, it will either all or none of them will be called.

The complete lifecycle of a component from initialization to activation to final destruction is called onLoad -> onEnable -> start -> update -> lateUpdate -> onDisable -> onDestroy.

Of these, onLoad and start are often used to initialize components, and can only be called with the node activeInHierarchy, and will only be called once at most. In addition to the above and the order in which they are called, there are the following differences:

Node activation Is called only when the component is enabled?
onLoad Immediately call no
start Delay call is