Cocos Creator record six - component script

Script execution order

Using a unified control script to initialize other scripts

I generally will have a Game.js script as total control script, if I have Player.js, Enemy.js, Menu.js three components, their initialization process is as follows:

// Game.js

const Player = require('Player');
const Enemy = require('Enemy');
const Menu = require('Menu');

cc.Class({
    extends: cc.Component,
    properties: {
        player: Player,
        enemy: Enemy,
        menu: Menu
    },

    onLoad: function () {
        this.player.init();
        this.enemy.init();
        this.menu.init();
    }
});

Wherein Player.js, Enemy.js Menu.js and the need to implement the init method, and the initialization logic into them. This way we can guarantee initialization sequence Player, Enemy and the Menu.

In the method of controlling the Update with custom update sequence

Similarly if you want to update to ensure that the update sequence per frame than three scripts, we can also be dispersed in each script is replaced by their own definition of the method:

// Player.js
    updatePlayer: function (dt) {
        // do player update
    }

Then call these methods update Game.js's script:

// Game.js
    update: function (dt) {
        this.player.updatePlayer(dt);
        this.enemy.updateEnemy(dt);
        this.menu.updateMenu(dt);
    }

Execution order control components on the same node

Component script execution sequence on the same node, can be controlled by the components in the order in the property inspector. Assembly will be arranged on the arrangement of the components prior to the next execution. We can adjust the order of the components and the execution order by a gear assembly in the upper right button Move Up and Move Down menu.

Setting component execution priority

If the above method still can not provide the desired particle size control can also be provided directly executionOrder assembly. executionOrder will affect the life cycle of components callback execution priority. Set as follows:

// Player.js

cc.Class({
    extends: cc.Component,
    editor: {
        executionOrder: -1
    },

    onLoad: function () {
        cc.log('Player onLoad!');
    }
});
// Menu.js

cc.Class({
    extends: cc.Component,
    editor: {
        executionOrder: 1
    },

    onLoad: function () {
        cc.log('Menu onLoad!');
    }
});

executionOrder smaller, the more the first component relative to other components of execution. executionOrder default is 0, so a negative number, then the default will be executed before the other components. executionOrder only onLoad, onEnable, start, update and lateUpdate effective for onDisable and onDestroy invalid.

Guess you like

Origin blog.csdn.net/zhengjuqiang/article/details/80842710