生命周期回调
Cocos Creator 为组件脚本提供了生命周期的回调函数。用户只要定义特定的回调函数,Creator 就会在特定的时期自动执行相关脚本,用户不需要手工调用它们。 目前提供给用户的声明周期回调函数主要有:
- -
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时,会激活onEnable回调。倘若节点第一次被 创建且enabled为true,则会在onLoad之后,start之前被调用。onDisable
enabled属性从true变为false时,会激活onDisable回调。onDestroy
destroy(),会在该帧结束被统一回收,此时会调用onDestroy回调。
创建和销毁节点。
