Cocos Creator 生命周期回調(diào)(官方文檔摘錄)

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)建且 enabledtrue,則會(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)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容