十分好奇,如何实现脚本的生命周期

如题所述,请满足我的好奇心。谢谢大佬。

看引擎实现中的 node-activator.ts 和 component-scheduler.ts

Cocos Creator引擎为组件设计了7个特定的回调函数,会在特定时期自动执行,不需要用户手工调用。

  • onLoad:节点首次激活时触发
  • onEnable:在组件激活时触发
  • start:在onEnable之后触发(仅一次)
  • update: 每帧触发
  • lateUpdate: update之后触发
  • onDisable: 组件禁用时触发
  • onDestroy: 节点销毁时触发
cc.Class({
    extends: cc.Component,
  
    onLoad() {
        this._flag = 0;
        cc.log('onLoad');
    },
    onEnable() {
        cc.log('onEnable');
    },
    onDisable() {
        cc.log('onDisable');
    }, 
    start() {
        cc.log('start');
    },
    update() {
        cc.log('update');

        this._flag++;
        if (this._flag > 10) {
            this.node.destroy();
        }
    },
    lateUpdate() {
        cc.log('lateUpdate');
    },
    onDestroy() {
        cc.log('onDestroy');
    }
});

大佬我问的是底层实现。。。

底层是在 创建、销毁、每帧事件中执行的回调函数,伪代码:

let a = new xxx();
a.onLoad();
...
a.onEnable();
...
a.onDestroy();
delete a;

【CCGame.js】

_runMainLoop() => window.requestAnimFrame(callback) => director.mainLoop()

【CCDirector.js】

this._compScheduler.updatePhase(this._deltaTime)

【component-scheduler.js】

this.updateInvoker.invoke(dt) => LifeCycleInvoker._invoke() => invokeUpdate => component.update(dt)

还有些其他东西,需要看源码