Cocos Creator 為組件腳本提供了生命周期的回調(diào)函數(shù)。用戶通過(guò)定義特定的函數(shù)回調(diào)在特定的時(shí)期編寫相關(guān) 腳本。目前提供給用戶的聲明周期回調(diào)函數(shù)有:
- onLoad
- start
- update
- lateUpdate
- onDestroy
- onEnable
- onDisable
onLoad
組件腳本的初始化階段,我們提供了 onLoad 回調(diào)函數(shù)。onLoad 回調(diào)會(huì)在這個(gè)組件所在的場(chǎng)景被載入 的時(shí)候觸發(fā),在 onLoad 階段,保證了你可以獲取到場(chǎng)景中的其他節(jié)點(diǎn),以及節(jié)點(diǎn)關(guān)聯(lián)的資源數(shù)據(jù)。通常 我們會(huì)在 onLoad階段去做一些初始化相關(guān)的操作。例如:
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 回調(diào)函數(shù)會(huì)在組件第一次激活前,也就是第一次執(zhí)行 update 之前觸發(fā)。**start**** 通常用于 初始化一些中間狀態(tài)的數(shù)據(jù)**,這些數(shù)據(jù)可能在 update 時(shí)會(huì)發(fā)生改變,并且被頻繁的 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
游戲開發(fā)的一個(gè)關(guān)鍵點(diǎn)是在每一幀渲染前更新物體的行為,狀態(tài)和方位。這些更新操作通常都放在 update 回調(diào)中。
cc.Class({ extends: cc.Component, update: function (dt) { this.node.setPosition( 0.0, 40.0 * dt ); }});
lateUpdate
update 會(huì)在所有動(dòng)畫更新前執(zhí)行,但如果我們要在動(dòng)畫更新之后才進(jìn)行一些額外操作,或者希望在所有組件的 update 都執(zhí)行完之后才進(jìn)行其它操作,那就需要用到 lateUpdate 回調(diào)。
cc.Class({ extends: cc.Component, lateUpdate: function (dt) { this.node.rotation = 20; }});
onEnable
當(dāng)組件的 enabled 屬性從 false 變?yōu)?true 時(shí),會(huì)激活 onEnable 回調(diào)。倘若節(jié)點(diǎn)第一次被 創(chuàng)建且 enabled 為 true,則會(huì)在 onLoad 之后,start 之前被調(diào)用。
onDisable
當(dāng)組件的 enabled 屬性從 true 變?yōu)?false 時(shí),會(huì)激活 onDisable 回調(diào)。
onDestroy
當(dāng)組件調(diào)用了 destroy(),會(huì)在該幀結(jié)束被統(tǒng)一回收,此時(shí)會(huì)調(diào)用 onDestroy 回調(diào)。