好久没有使用 Cocos Creator 开发小游戏,今天重新下载了最新的版本 v3.8.3,创建了一个空的2D 工程,并且在场景中增加了一个 Label 组件,文本内容修改为“Hello World”,看起来一切都平平无奇。
但是,预览的时候 Chrome 浏览器始终处于加载状态(白屏)。
回到 Cocos Creator,发现控制台有如下报错:o.deviceConfig.forEach is not a function,展开查看具体报错信息如下:
TypeError: o.deviceConfig.forEach is not a function
at Package.query (/Applications/Cocos/Creator/3.8.3/CocosCreator.app/Contents/Resources/app.asar/modules/editor-extensions/extensions/device/dist/browser/index.ccc:1:238)
at /Applications/Cocos/Creator/3.8.3/CocosCreator.app/Contents/Resources/app.asar/node_modules/@editor/package/dist/browser/index.js:1:2955
(Target: device, Message: query)
最终发现,原因是我的机器当前没有联网(无外网访问权限,谁能想到程序员的电脑居然会没网啊,哈哈,所以算是比较极端的情况了),这种情况下 v3.8.3 存在一个 BUG 会导致这个问题的产生。
解决方案
官方提供的解决方案是,在当前的项目下临时安装一个扩展来解决,然后等着下个版本修复此 BUG。
插件地址:forum.cocos.org/uploads/sho…
下载这个插件,解压后放到项目根目录下的 extensions 目录中即可(如下图)
记得要重新打开 Cocos Creator 以确保插件生效,插件并不是即刻生效的。
官方论坛帖子见:forum.cocos.org/t/topic/157…
插件源码
看了一下插件源码,就是对异常数据做了一下检查,如果发现报错,就直接返回了(行9~行16)
exports.load = async function () {
const deviceConfig = await Editor.Profile.getConfig('device', 'deviceConfig', 'default');
if (!Array.isArray(deviceConfig) && Array.isArray(deviceConfig.devices)) {
await Editor.Profile.setConfig('device', 'deviceConfig', deviceConfig.devices, 'default');
const enableDevice = {};
deviceConfig.devices.forEach((info) => {
// 做一次检查避免异常数据
if (!info.name
|| typeof(info.width) !== 'number'
|| typeof(info.height) !== 'number'
|| typeof(info.ratio) !== 'number'
) {
console.warn(`Invalid device data ${JSON.stringify(info)}`);
return;
}
if (info.enable) {
enableDevice[info.name] = true;
}
});
await Editor.Profile.setConfig('device', 'enableDevice', enableDevice, 'default');
console.log('fix device list success');
}
}