推荐一个调试时方便快速编译脚本的方法

在编写代码后调试,我们为了代码能生效,需要切到Cocos Creator编译预览脚本,

或者你配置了VS Code 激活脚本编译,使用快捷键编译。

这里介绍一个直接在网页上快速编译的方法,以2.4.x为例

修改预览模板的boot.js,它在编辑器路径 editors\Creator\2.4.x\resources\static\preview-templates下,修改boot.js的258行开始代码,然后就可以使用快捷键编译刷新了(我这里改的键是Ctrl + P)


// 原代码

// init recompile button

btnRecompile.addEventListener('click', function () {

    var url = window.location.href + 'update-db';

    var xmlHttp = new XMLHttpRequest();

    xmlHttp.onreadystatechange = function () {

        if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {

            document.getElementById('recompiling').style.display = 'block';

        }

    };

    xmlHttp.open("GET", url, true); // true for asynchronous

    xmlHttp.send(null);

});


// 改动后

function recompile() {

    var url = window.location.href + 'update-db';

    var xmlHttp = new XMLHttpRequest();

    xmlHttp.onreadystatechange = function () {

        if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {

            document.getElementById('recompiling').style.display = 'block';

            console.log("recompile success")

            location.reload();

        }

    };

    xmlHttp.open("GET", url, true); // true for asynchronous

    xmlHttp.send(null);

}

document.addEventListener('keydown', function(event) {

    // 检查是否按下了 Ctrl 键和 P c

    if (event.ctrlKey && event.key === 'p') {

        // 阻止默认的行为

        event.preventDefault();

        console.log('Ctrl + P 被按下');

        recompile();

    }

});

btnRecompile.addEventListener('click', recompile);

原理很简单,creator编辑器暴露了接口http://localhost:7456/update-db,调该接口就能刷新界面了,3.8.x应该同理,不过得先加自定义预览模板,加下recompile函数和keydown事件就行,注意,creator 3.8.x的版本编译接口改成http://localhost:7456/asset-db/refresh

4赞