Cocos Creator 為組件腳本提供了生命周期的回調函數。用戶只要定義特定的回調函數,Creator 就會在特定的時期自動執行相關腳本,用戶不需要手工調用它們。
目前提供給用戶的生命周期回調函數主要有:
* onLoad
* start
* update
* lateUpdate
* onDestroy
* onEnable
* onDisable
*
## onLoad
組件腳本的初始化階段,我們提供了 `onLoad` 回調函數。`onLoad` 回調會在組件首次激活時觸發,比如所在的場景被載入,或者所在節點被激活的情況下。在 `onLoad` 階段,保證了你可以獲取到場景中的其他節點,以及節點關聯的資源數據。`onLoad` 總是會在任何 `start` 方法調用前執行,這能用于安排腳本的初始化順序。通常我們會在 `onLoad` 階段去做一些初始化相關的操作。例如:
~~~
cc.Class({
extends: cc.Component,
properties: {
bulletSprite: cc.SpriteFrame,
gun: cc.Node,
},
onLoad: function () {
this._bulletRect = this.bulletSprite.getRect();
this.gun = cc.find('hand/weapon', this.node);
},
});
~~~
## start
`start` 回調函數會在組件第一次激活前,也就是第一次執行 `update` 之前觸發。`start` 通常用于初始化一些中間狀態的數據,這些數據可能在 `update` 時會發生改變,并且被頻繁的 enable和 disable。
~~~
cc.Class({
extends: cc.Component,
start: function () {
this._timer = 0.0;
},
update: function (dt) {
this._timer += dt;
if ( this._timer >= 10.0 ) {
console.log('I am done!');
this.enabled = false;
}
},
});
~~~
## update
游戲開發的一個關鍵點是在每一幀渲染前更新物體的行為,狀態和方位。這些更新操作通常都放在 `update` 回調中。
~~~
cc.Class({
extends: cc.Component,
update: function (dt) {
this.node.setPosition( 0.0, 40.0 * dt );
}
});
~~~
## lateUpdate
`update` 會在所有動畫更新前執行,但如果我們要在動畫更新之后才進行一些額外操作,或者希望在所有組件的 `update` 都執行完之后才進行其它操作,那就需要用到 lateUpdate 回調。
~~~
cc.Class({
extends: cc.Component,
lateUpdate: function (dt) {
this.node.rotation = 20;
}
});
~~~
## onEnable
當組件的 `enabled` 屬性從 false 變為 true 時,或者所在節點的 `active` 屬性從 false 變為 true 時,會激活 `onEnable` 回調。倘若節點第一次被創建且 enabled 為 true,則會在 `onLoad` 之后,start 之前被調用。
## onDisable
當組件的 `enabled` 屬性從 true 變為 false 時,或者所在節點的 `active` 屬性從 true 變為 false 時,會激活 `onDisable` 回調。
## onDestroy
當組件或者所在節點調用了 `destroy()`,則會調用 `onDestroy` 回調,并在當幀結束時統一回收組件。