--------- beginning of system --------- beginning of main ---------------------------- PROCESS STARTED (3330) for package org.cocos2d.demo ---------------------------- 2025-07-15 15:48:35.316 3330-3359 eglCodecCommon org.cocos2d.demo E glUtilsParamSize: unknow param 0x000082da 2025-07-15 15:48:35.316 3330-3359 eglCodecCommon org.cocos2d.demo E glUtilsParamSize: unknow param 0x000082e5 2025-07-15 15:48:35.328 3330-3359 eglCodecCommon org.cocos2d.demo E glUtilsParamSize: unknow param 0x00008c29 2025-07-15 15:48:35.328 3330-3359 eglCodecCommon org.cocos2d.demo E glUtilsParamSize: unknow param 0x000087fe 2025-07-15 15:48:35.363 3330-3359 EGL_emulation org.cocos2d.demo E tid 3359: eglSurfaceAttrib(1493): error 0x3009 (EGL_BAD_MATCH) 2025-07-15 15:48:36.976 3330-3357 jswrapper org.cocos2d.demo E ScriptEngine::onGetStringFromFile stream not found, possible missing file. 2025-07-15 15:48:36.976 3330-3357 jswrapper org.cocos2d.demo E ScriptEngine::runScript script stream, buffer is empty! 2025-07-15 15:48:36.976 3330-3357 jswrapper org.cocos2d.demo E [ERROR] Failed to invoke require, location: C:/ProgramData/cocos/editors/Creator/2.4.13/resources/cocos2d-x/cocos/scripting/js-bindings/manual/jsb_global.cpp:299 2025-07-15 15:48:37.026 3330-3357 jswrapper org.cocos2d.demo E ScriptEngine::evalString catch exception: 2025-07-15 15:48:37.050 3330-3357 jswrapper org.cocos2d.demo E ERROR: Uncaught ReferenceError: self is not defined, location: src/assets/_plugs/lib/gravityengine.mg.cocoscreator.min.dbb97.js:0:0 STACK: [0]anonymous@src/assets/_plugs/lib/gravityengine.mg.cocoscreator.min.dbb97.js:2 [1]anonymous@src/assets/_plugs/lib/gravityengine.mg.cocoscreator.min.dbb97.js:3 [2]anonymous@jsb-adapter/jsb-engine.js:2975 [3]download@jsb-adapter/jsb-engine.js:2984 [4]downloadScript@jsb-adapter/jsb-engine.js:2971 [5]a@src/cocos2d-jsb.28d62.js:16668 [6]anonymous@src/cocos2d-jsb.28d62.js:16678 [7]retry@src/cocos2d-jsb.28d62.js:18111 [8]download@src/cocos2d-jsb.28d62.js:16663 [9]load@src/cocos2d-jsb.28d62.js:17318 [10]94.e.exports@src/cocos2d-jsb.28d62.js:17134 [11]_flow@src/cocos2d-jsb.28d62.js:17579 [12]async@src/cocos2d-jsb.28d62.js:17574 [13]anonymous@src/cocos2d-jsb.28d62.js:17261 [14]forEach@src/cocos2d-jsb.28d62.js:18189 [15]94.e.exports@src/cocos2d-jsb.28d62.js:17244 [16]_flow@src/cocos2d-jsb.28d62.js:17579 [17]anonymous@src/cocos2d-jsb.28d62.js:17586 [18]98.e.exports@src/cocos2d-jsb.2 2025-07-15 15:48:37.052 3330-3357 jswrapper org.cocos2d.demo E ScriptEngine::evalString script src/assets/_plugs/lib/gravityengine.mg.cocoscreator.min.dbb97.js, failed! 2025-07-15 15:48:37.053 3330-3357 jswrapper org.cocos2d.demo E [ERROR] Failed to invoke require, location: C:/ProgramData/cocos/editors/Creator/2.4.13/resources/cocos2d-x/cocos/scripting/js-bindings/manual/jsb_global.cpp:299 2025-07-15 15:48:49.228 1715-2033 bt_btif com.android.bluetooth E register_notification_rsp: Avrcp device is not connected, handle: 0x0 2025-07-15 15:48:49.228 1715-2033 bt_btif com.android.bluetooth E register_notification_rsp: Avrcp device is not connected, handle: 0x0 2025-07-15 15:48:49.241 1452-1763 OMXNodeInstance media.codec E setConfig(0xf5210060:google.mp3.decoder, ConfigPriority(0x6f800002)) ERROR: Undefined(0x80001001) 2025-07-15 15:48:49.241 1452-1763 OMXNodeInstance media.codec E getConfig(0xf5210060:google.mp3.decoder, ConfigAndroidVendorExtension(0x6f100004)) ERROR: Undefined(0x80001001) 2025-07-15 15:49:00.001 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.015 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.024 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.037 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.045 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.054 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.061 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.071 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.081 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.091 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.107 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.115 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.123 1573-1586 memtrack system_server E Couldn't load memtrack module 2025-07-15 15:49:00.132 1573-1586 memtrack system_server E Couldn't load memtrack module
时间: 2025-07-20 21:27:12 浏览: 5
<think>根据错误日志,问题发生在加载重力引擎SDK时,具体错误是:
ERROR: Uncaught ReferenceError: self is not defined, location: src/assets/_plugs/lib/gravityengine.mg.cocoscreator.min.dbb97.js:0:0
尽管我们之前已经做了全局对象修复,但错误仍然出现。这可能是由于:
1. 全局修复代码执行时机太晚,在SDK加载之前环境没有准备好
2. 在Cocos Creator原生环境中,JS引擎(如V8)对全局对象的处理与浏览器不同
解决方案:
我们将在重力引擎SDK文件的开头注入一段修复代码,确保在任何代码执行前就定义好`self`。
步骤:
1. 修改重力引擎SDK文件(gravityengine.mg.cocoscreator.min.js),在文件最开头添加全局修复代码
2. 如果无法修改SDK文件,则使用一个包装器文件来包裹SDK
### 方案1:直接修改SDK文件(推荐)
在重力引擎SDK文件(gravityengine.mg.cocoscreator.min.js)的最开头添加以下代码:
```javascript
// 在SDK文件开头添加
(function() {
// 确保self存在
if (typeof self === 'undefined') {
// 尝试获取全局对象
var globalObj = (function() {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof global !== 'undefined') return global;
if (typeof window !== 'undefined') return window;
// 最后,如果都没有,创建一个新对象(但这种情况应该不会发生)
return Function('return this')();
})();
// 定义self
Object.defineProperty(globalObj, 'self', {
value: globalObj,
writable: true,
configurable: true,
enumerable: true
});
}
})();
```
### 方案2:使用包装器文件(如果无法修改原SDK)
创建一个新的包装器文件,例如`gravityengine-wrapper.js`,内容如下:
```javascript
// 确保全局对象存在
(function(global) {
// 如果global未定义,则创建一个(在严格模式下,this可能是undefined)
if (typeof global === 'undefined') {
global = Function('return this')() || {};
}
// 确保self存在
if (typeof self === 'undefined') {
global.self = global;
}
// 加载原始SDK
require('./gravityengine.mg.cocoscreator.min.js');
// 将GravityEngine导出为模块(如果需要)
if (typeof module !== 'undefined' && module.exports) {
module.exports = global.GravityEngine;
}
})(this);
```
然后,修改SDK加载路径,优先加载包装器文件:
```javascript
const sdkPaths = [
'./assets/_plugs/lib/gravityengine-wrapper.js', // 使用包装器
'./assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js',
'_plugs/lib/gravityengine.mg.cocoscreator.min.js',
'lib/gravityengine.mg.cocoscreator.min.js'
];
```
### 完整修复后的入口代码(包含之前的全局修复和包装器方案)
由于错误日志显示问题出现在SDK内部,我们采用方案2(包装器)更为稳妥,因为不需要修改第三方SDK。
以下是完整的入口代码,已包含包装器方案:
```javascript
// ====== 环境修复与全局对象安全 ======
(function() {
// 安全获取全局对象的函数(支持严格模式和所有环境)
const getGlobalObject = () => {
// 1. 优先使用现代标准 globalThis
if (typeof globalThis !== 'undefined') return globalThis;
// 2. 处理严格模式限制
try {
const globalFromFn = Function('return this')();
if (globalFromFn) return globalFromFn;
} catch (e) {
console.warn('[EnvFix] Function constructor blocked in strict mode');
}
// 3. 环境特定对象
if (typeof global !== 'undefined') return global; // Node.js
if (typeof window !== 'undefined') return window; // 浏览器
if (typeof self !== 'undefined') return self; // Web Worker
// 4. Cocos Creator 原生环境特殊处理
if (typeof cc !== 'undefined' && cc.sys && cc.sys.__globalAdapter) {
return cc.sys.__globalAdapter;
}
// 5. 最后手段:创建新的全局对象
console.error('[EnvFix] Unable to determine global object, creating new');
return {};
};
const globalObj = getGlobalObject();
// 修复关键全局变量(使用 Object.defineProperty 防止覆盖)
const defineGlobal = (name, value) => {
if (typeof globalObj[name] === 'undefined') {
Object.defineProperty(globalObj, name, {
value,
writable: true,
configurable: true,
enumerable: true
});
console.log(`[EnvFix] Defined global: ${name}`);
}
};
// 定义关键全局对象
defineGlobal('global', globalObj);
defineGlobal('self', globalObj);
defineGlobal('globalThis', globalObj);
defineGlobal('window', globalObj);
// 原生平台特殊处理
if (cc && cc.sys && cc.sys.isNative) {
// 确保 XMLHttpRequest 存在
if (typeof XMLHttpRequest === 'undefined') {
defineGlobal('XMLHttpRequest', function() {
return cc.loader.getXMLHttpRequest();
});
}
// 确保 document 对象存在
if (typeof document === 'undefined') {
defineGlobal('document', {
createElement: () => ({ appendChild: () => {} }),
head: { appendChild: () => {} },
body: { appendChild: () => {} }
});
}
// 确保 location 对象存在
if (typeof location === 'undefined') {
defineGlobal('location', {
href: 'file://',
protocol: 'file:',
hostname: 'localhost',
host: 'localhost',
origin: 'file://'
});
}
console.log('[EnvFix] Native environment patched');
}
// 确保 require 函数存在
if (typeof globalObj.require === 'undefined') {
defineGlobal('require', function(module) {
if (globalObj.__modules && globalObj.__modules[module]) {
return globalObj.__modules[module];
}
console.warn(`[RequireFallback] Module '${module}' not found`);
return {};
});
}
})();
// ====== 引擎初始化保护系统 ======
const EngineReady = (function() {
let _promise = null;
let _resolve = null;
let _isReady = false;
let _checkInterval = null;
const safeCheckEngine = () => {
// 引擎已初始化
if (cc && cc.game && cc.game._isEngineInited) {
return true;
}
// 尝试监听初始化事件
if (cc && cc.game && cc.game.once) {
const eventName = cc.game.EVENT_ENGINE_INITED || 'engine-inited';
cc.game.once(eventName, () => {
_resolve && _resolve();
_isReady = true;
_checkInterval && clearInterval(_checkInterval);
});
return true;
}
return false;
};
return {
get isReady() { return _isReady; },
get promise() { return _promise; },
init() {
if (!_promise) {
_promise = new Promise(resolve => {
_resolve = () => {
_isReady = true;
resolve();
_checkInterval && clearInterval(_checkInterval);
};
// 首次检查
if (safeCheckEngine()) return;
// 轮询检查
_checkInterval = setInterval(() => {
safeCheckEngine() && _resolve();
}, 100);
});
}
return _promise;
},
safeAccess(callback) {
if (_isReady) {
try {
return callback();
} catch (e) {
console.error('[EngineSafe] Error:', e);
}
}
return _promise.then(callback).catch(e => {
console.error('[EngineSafe] Async error:', e);
});
}
};
})();
EngineReady.init();
// ====== 游戏主入口 ======
async function gameMainEntry() {
try {
console.log('[Main] Waiting for engine initialization...');
await EngineReady.promise;
console.log('[Main] Engine ready');
// 基本引擎配置
EngineReady.safeAccess(() => {
if (cc.view) {
cc.view.enableRetina(true);
cc.view.resizeWithBrowserSize(true);
cc.view.setDesignResolutionSize(960, 640, cc.ResolutionPolicy.SHOW_ALL);
}
});
// 加载SDK
await loadGravityEngineSDK();
// 加载启动场景
await loadStartScene();
} catch (error) {
console.error('[Main] Initialization failed:', error);
try {
cc.director.loadScene('start');
} catch (fallbackError) {
displayErrorFallback('启动失败\n请重启应用');
}
}
}
// 错误显示后备方案
function displayErrorFallback(message) {
try {
const errorDiv = document.createElement('div');
errorDiv.style.cssText = `
position: fixed;
top: 0; left: 0;
width: 100%; height: 100%;
background: black;
color: white;
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
font: 24px Arial, sans-serif;
text-align: center;
white-space: pre-line;
padding: 20px;
`;
errorDiv.textContent = message;
document.body.appendChild(errorDiv);
} catch (e) {
console.error('[Fallback] Display failed:', e);
}
}
// ====== SDK加载器增强版 ======
async function loadGravityEngineSDK() {
// 使用相对路径解决加载问题,优先使用包装器
const sdkPaths = [
'./assets/_plugs/lib/gravityengine-wrapper.js', // 包装器文件
'./assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js',
'_plugs/lib/gravityengine.mg.cocoscreator.min.js',
'lib/gravityengine.mg.cocoscreator.min.js'
];
for (const path of sdkPaths) {
try {
// 关键修复:在加载 SDK 前确保全局对象完整
ensureGlobalEnvironment();
await loadScript(path);
console.log('[SDK] Loaded from:', path);
// 关键修复:加载后再次检查全局对象
ensureGlobalEnvironment();
initGravityEngine();
return;
} catch (e) {
console.warn('[SDK] Load failed:', path, e.message);
}
}
console.error('[SDK] All paths failed');
handleSDKLoadFailure();
}
function ensureGlobalEnvironment() {
// 获取全局对象
const getGlobalObject = () => {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof global !== 'undefined') return global;
if (typeof window !== 'undefined') return window;
if (typeof self !== 'undefined') return self;
return Function('return this')() || {};
};
const globalObj = getGlobalObject();
// 确保 self 在所有环境中都存在
if (typeof self === 'undefined') {
console.warn('[GlobalFix] self is undefined, patching...');
Object.defineProperty(globalObj, 'self', {
value: globalObj,
writable: true,
configurable: true,
enumerable: true
});
}
// 确保其他关键全局对象存在
const requiredGlobals = ['window', 'global', 'globalThis', 'document', 'location'];
requiredGlobals.forEach(name => {
if (typeof globalObj[name] === 'undefined') {
console.warn(`[GlobalFix] ${name} is undefined, patching...`);
Object.defineProperty(globalObj, name, {
value: globalObj,
writable: true,
configurable: true,
enumerable: true
});
}
});
// 原生平台特殊处理
if (cc && cc.sys && cc.sys.isNative) {
// 确保 location 对象存在
if (typeof location === 'undefined') {
Object.defineProperty(globalObj, 'location', {
value: {
href: 'file://',
protocol: 'file:',
hostname: 'localhost'
},
writable: false,
configurable: false,
enumerable: true
});
}
}
}
function loadScript(path) {
return new Promise((resolve, reject) => {
// 优先使用 Cocos 的加载系统
if (cc.assetManager?.loadScript) {
cc.assetManager.loadScript(path, (err) => {
if (err) {
// 原生平台特殊处理
if (cc.sys.isNative) {
console.warn('[SDK] Using native fallback for script loading');
try {
// 原生平台直接执行脚本
const jsb = cc.sys.__globalAdapter;
if (jsb && jsb.require) {
jsb.require(path);
return resolve();
}
} catch (nativeError) {
console.error('[SDK] Native require failed:', nativeError);
}
}
reject(err);
} else {
resolve();
}
});
return;
}
// 后备方案:直接创建 script 标签
try {
const script = document.createElement('script');
script.src = path;
script.onload = () => resolve();
script.onerror = () => reject(new Error(`Failed to load ${path}`));
document.head.appendChild(script);
console.warn('[SDK] Using DOM fallback for script loading');
} catch (e) {
reject(e);
}
});
}
function initGravityEngine() {
let GravityEngine = null;
// 1. 尝试标准方式获取
if (typeof GravityEngine === 'function') {
console.log('[SDK] GravityEngine found in local scope');
}
// 2. 尝试从全局对象中查找
else if (typeof window.GravityEngine === 'function') {
GravityEngine = window.GravityEngine;
console.warn('[SDK] Found GravityEngine in window object');
}
// 3. 尝试从其他全局对象中查找
else if (typeof global.GravityEngine === 'function') {
GravityEngine = global.GravityEngine;
console.warn('[SDK] Found GravityEngine in global object');
}
// 4. 尝试从 self 对象中查找
else if (typeof self.GravityEngine === 'function') {
GravityEngine = self.GravityEngine;
console.warn('[SDK] Found GravityEngine in self object');
}
// 5. 最后尝试从 globalThis 中查找
else if (typeof globalThis.GravityEngine === 'function') {
GravityEngine = globalThis.GravityEngine;
console.warn('[SDK] Found GravityEngine in globalThis object');
}
else {
console.error('[SDK] GravityEngine not found');
return;
}
try {
// 使用您的 AppID 624768904
GravityEngine.init({
appId: '624768904',
enableLog: true
});
console.log('[SDK] GravityEngine initialized with AppID 624768904');
} catch (e) {
console.error('[SDK] Init failed:', e);
}
}
function handleSDKLoadFailure() {
console.warn('[SDK] Using fallback analytics');
window.GravityEngine = {
init: () => console.warn('SDK unavailable'),
trackEvent: () => {}
};
}
// ====== 场景加载器 ======
async function loadStartScene() {
try {
// 加载主资源包
await new Promise((resolve) => {
if (!cc.assetManager?.loadBundle) {
console.warn('[Scene] AssetManager unavailable');
return resolve();
}
cc.assetManager.loadBundle('main', (err) => {
if (err) console.error('[Scene] Bundle load error:', err);
resolve();
});
});
// 加载场景
if (cc.director?.loadScene) {
cc.director.loadScene('start');
} else {
throw new Error('Director unavailable');
}
} catch (error) {
console.error('[Scene] Load failed:', error);
try {
cc.director.loadScene('start');
} catch (e) {
throw new Error('Fallback scene load failed');
}
}
}
// ====== UI_Entry组件 ======
const { ccclass, property } = cc._decorator;
@ccclass
export default class UI_Entry extends cc.Component {
@property(cc.ProgressBar)
progress_loading = null;
loginTimeoutHandler = null;
onLoad() {
EngineReady.safeAccess(() => {
try {
cc.director.getCollisionManager().enabled = true;
this._show();
} catch (e) {
console.error('[UI] onLoad error:', e);
this.startLoadGame();
}
}).catch(e => {
console.error('[UI] Engine access error:', e);
this.startLoadGame();
});
}
onDestroy() {
this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler);
}
async _show() {
this.progress_loading.progress = 0;
// 平台SDK初始化
if (cc.sys.isBrowser) {
try {
await this.initYPSDK();
} catch (e) {
console.error('[YPSDK] Init failed:', e);
this.startLoadGame();
}
} else {
this.startLoadGame();
}
// 登录超时保护
this.setLoginTimeout();
}
setLoginTimeout() {
if (cc.tween) {
this.loginTimeoutHandler = cc.tween(this)
.delay(10)
.call(() => {
console.warn('[Login] Timeout after 10s');
this.startLoadGame();
})
.start();
} else {
setTimeout(() => this.startLoadGame(), 10000);
}
}
async initYPSDK() {
if (typeof YPSDK === 'undefined') {
console.warn('[YPSDK] SDK unavailable');
return;
}
const config = {
gameChannelList: {
h5: { platformType: "h5", version: "1.0.0" },
tt: { platformType: "tt", appId: "tt09297f94961f881b02" },
wx: { platformType: "wx", appId: "wx6baaaa27ab5186ff" }
}
};
await YPSDK.init(39, "https://platform-shop-dev.hanyougame.com", config);
await YPSDK.login();
if (YPSDK.setLoginCallBack) {
YPSDK.setLoginCallBack(success => {
if (!success) return;
// 取消超时
this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler);
// 初始化分析SDK
if (r_GravityPlatform.default?.GA_Init) {
r_GravityPlatform.default.GA_Init(YPSDK.Platform.loginData.bindingId);
}
this.startLoadGame();
});
} else {
this.startLoadGame();
}
}
startLoadGame() {
const tasks = [
this._loadGameConfig,
this._loadRemoteConfig,
this._loadExcelData,
this._loadUserData,
this._loadCommonBundle,
this._loadMainBundle
].map(fn => fn.bind(this));
this.executeTasks(tasks, () => this._loadGame());
}
executeTasks(tasks, finalCallback) {
let completed = 0;
const total = tasks.length;
const runTask = async (index) => {
if (index >= total) {
finalCallback();
return;
}
try {
await tasks[index]();
completed++;
this._setProgress(completed / total);
runTask(index + 1);
} catch (e) {
console.error(`[Task ${index}] Failed:`, e);
completed++;
this._setProgress(completed / total);
runTask(index + 1); // 继续执行后续任务
}
};
runTask(0);
}
async _loadExcelData() {
if (!r_ExcelLoader?.ExcelLoader?.loadAll) {
console.warn('[Data] ExcelLoader unavailable');
return;
}
await r_ExcelLoader.ExcelLoader.loadAll();
console.log('[Data] Excel loaded');
}
async _loadGameConfig() {
if (!r_ResLoader.default?.loadRes) {
console.warn('[Config] ResLoader unavailable');
return;
}
const jsonAsset = await r_ResLoader.default.loadRes(
"resources",
"config/GameConfig",
cc.JsonAsset
);
if (jsonAsset && r_GameConfig.default) {
r_GameConfig.default.appConfig = jsonAsset.json;
jsonAsset.decRef && jsonAsset.decRef();
console.log('[Config] Game config loaded');
}
}
async _loadRemoteConfig() {
if (!r_GameConfig.default?.appConfig?.RemoteUrl) {
console.warn('[Config] RemoteUrl not set');
return;
}
const remoteUrl = r_GameConfig.default.appConfig.RemoteUrl;
const remotePath = cc.path.join(remoteUrl, "ADConfig.json");
try {
const remoteConfig = await r_ResLoader.default.loadRemote(remotePath, { ext: ".json" });
if (remoteConfig?.json && r_GravityPlatform.default) {
r_GravityPlatform.default.videoId = remoteConfig.json.ADUnitId[0];
r_GameConfig.default.adConfig = remoteConfig.json;
console.log('[Config] Remote config loaded');
}
} catch (e) {
console.error('[Config] Remote load failed:', e);
}
}
async _loadCommonBundle() {
if (!r_ResLoader.default?.loadBundle) {
console.warn('[Bundle] ResLoader unavailable');
return;
}
try {
await r_ResLoader.default.loadBundle(r_BundleConfig.BundleNames.Common);
console.log('[Bundle] Common loaded');
} catch (e) {
console.error('[Bundle] Common load failed:', e);
}
}
async _loadMainBundle() {
if (!r_ResLoader.default?.loadBundle) {
console.warn('[Bundle] ResLoader unavailable');
return;
}
try {
await r_ResLoader.default.loadBundle(r_BundleConfig.MainGameBundle);
console.log('[Bundle] Main loaded');
} catch (e) {
console.error('[Bundle] Main load failed:', e);
}
}
async _loadUserData() {
try {
// 音频初始化
r_AudioManager.AudioMgr?.init();
// 全局配置
r_GameGlobalVariable.GameGlobalVariable?.initPeiZhi();
// 网络检测
if (YPSDK?.Common?.curChannelData) {
const platformType = YPSDK.Common.curChannelData.platformType;
if (platformType === YPSDK.GamePlatformType.WX || platformType === YPSDK.GamePlatformType.TT) {
r_YpNetMag.YpNetMag?.failSever(() => {
r_YpNetMag.YpNetMag.isFail = true;
});
}
}
// 用户数据初始化
if (YPSDK?.Platform?.loginData) {
await r_YpNetMag.YpNetMag?.initServer(YPSDK.Platform.loginData);
}
} catch (e) {
console.error('[User] Load failed:', e);
}
}
_loadGame() {
try {
const guideIndex = r_PlayerDataManager.PlayerDataMgr.GetGuideIndexByTaskName(
r_Const_Common.GuideName.战斗背包
);
if (guideIndex !== r_Const_Common.GameBagGuideIndex.引导完结) {
// 新玩家流程
r_PlayerDataManager.PlayerDataMgr.GMSetGuideIndex?.(
r_Const_Common.GuideName.战斗背包,
r_Const_Common.GameBagGuideIndex.引导初始1
);
r_GameDataManager.GameDataMgr?.ClearGameBagData();
r_GameGlobalVariable.GameGlobalVariable.nowlevel = 1;
r_UIManager.default?.open(
r_BundleConfig.BundleNames.Game,
r_UIConfig_Game.UIView_Game.UI_GameView
);
} else {
// 老玩家流程
r_EventManager.EventMgr?.dispatchEvent(r_EvenType.EVENT_TYPE.Game_Load_View, true);
r_UIManager.default?.open(
r_BundleConfig.BundleNames.Home,
r_UIConfig_Home.UIView_Home.UI_Hall
);
}
// 白名单检查
this.checkWhiteList();
} catch (e) {
console.error('[Game] Load failed:', e);
try {
cc.director.loadScene('start');
} catch (sceneError) {
console.error('[Game] Scene load failed:', sceneError);
}
}
}
async checkWhiteList() {
try {
if (!YPSDK?.Platform?.loginData || !YPSDK.platformUrl) return;
const url = `${YPSDK.platformUrl}/User/GetCfgData?userId=${YPSDK.Platform.loginData.userUid}&keyId=NoVideo`;
if (r_HttpManager.HttpMgr?.requestData) {
r_HttpManager.HttpMgr.requestData(res => {
if (res?.data?.keyData === "true") {
r_PlayerDataManager.PlayerDataMgr.WHITE_NAME_NO_VIDEO = true;
}
}, url);
}
} catch (e) {
console.error('[WhiteList] Check failed:', e);
}
}
_setProgress(progress) {
if (!this.progress_loading) return;
this.progress_loading.progress = Math.max(0, Math.min(1, progress));
}
}
// ====== 启动游戏 ======
if (cc?.game?.run) {
cc.game.run(() => {
// 确保环境修复完成
ensureGlobalEnvironment();
gameMainEntry();
});
} else {
setTimeout(() => {
ensureGlobalEnvironment();
gameMainEntry();
}, 1000);
}
```
### 额外步骤:创建包装器文件
在项目目录 `assets/_plugs/lib/` 下创建文件 `gravityengine-wrapper.js`,内容如下:
```javascript
// 确保全局对象存在
(function(global) {
// 如果global未定义,则创建一个(在严格模式下,this可能是undefined)
if (typeof global === 'undefined') {
global = (function() {
// 尝试各种方式获取全局对象
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof global !== 'undefined') return global;
if (typeof window !== 'undefined') return window;
if (typeof self !== 'undefined') return self;
return Function('return this')();
})();
}
// 确保self存在
if (typeof self === 'undefined') {
global.self = global;
}
// 加载原始SDK
require('./gravityengine.mg.cocoscreator.min.js');
// 将GravityEngine导出为模块(如果需要)
if (typeof module !== 'undefined' && module.exports) {
module.exports = global.GravityEngine;
}
})(this);
```
### 说明
1. **包装器作用**:
- 在加载重力引擎SDK之前,确保`self`全局变量存在
- 兼容各种JavaScript环境(浏览器、Node.js、Cocos原生等)
- 不修改原始SDK文件,便于更新和维护
2. **加载顺序**:
- 优先加载包装器文件 `gravityengine-wrapper.js`
- 包装器会加载原始SDK `gravityengine.mg.cocoscreator.min.js`
3. **全局修复**:
- 在游戏启动时执行全局环境修复
- 在加载SDK前再次确保环境安全
### 构建和测试
1. 将包装器文件放入正确位置
2. 更新入口代码(如上)
3. 清理构建缓存并重新构建
4. 在Android设备上测试运行
§§相关问题§§:
1. 在Cocos Creator中,如何处理第三方SDK的全局变量污染问题?
2. 如何调试Cocos Creator原生平台上的JavaScript错误?
3. 有哪些方法可以优化Cocos Creator游戏的启动时间?
4. 在跨平台开发中,如何确保JavaScript代码在不同环境(浏览器、原生)中的一致性?</think>根据错误日志,问题发生在加载重力引擎 SDK 时,具体错误是:
```
ERROR: Uncaught ReferenceError: self is not defined, location: src/assets/_plugs/lib/gravityengine.mg.cocoscreator.min.dbb97.js:0:0
```
尽管我们之前已经做了全局对象修复,但错误仍然出现。这是因为在 Cocos Creator 原生环境中,JSB 引擎的加载机制有特殊之处。以下是完整的修复方案:
```javascript
// ====== 环境修复与全局对象安全 ======
(function() {
// 安全获取全局对象的函数(支持严格模式和所有环境)
const getGlobalObject = () => {
// 1. 优先使用现代标准 globalThis
if (typeof globalThis !== 'undefined') return globalThis;
// 2. 处理严格模式限制
try {
const globalFromFn = Function('return this')();
if (globalFromFn) return globalFromFn;
} catch (e) {
console.warn('[EnvFix] Function constructor blocked in strict mode');
}
// 3. 环境特定对象
if (typeof global !== 'undefined') return global; // Node.js
if (typeof window !== 'undefined') return window; // 浏览器
if (typeof self !== 'undefined') return self; // Web Worker
// 4. Cocos Creator 原生环境特殊处理
if (typeof cc !== 'undefined' && cc.sys && cc.sys.__globalAdapter) {
return cc.sys.__globalAdapter;
}
// 5. 最后手段:创建新的全局对象
console.error('[EnvFix] Unable to determine global object, creating new');
return {};
};
const globalObj = getGlobalObject();
// 修复关键全局变量(使用 Object.defineProperty 防止覆盖)
const defineGlobal = (name, value) => {
if (typeof globalObj[name] === 'undefined') {
Object.defineProperty(globalObj, name, {
value,
writable: true,
configurable: true,
enumerable: true
});
console.log(`[EnvFix] Defined global: ${name}`);
}
};
// 定义关键全局对象
defineGlobal('global', globalObj);
defineGlobal('self', globalObj);
defineGlobal('globalThis', globalObj);
defineGlobal('window', globalObj);
// 原生平台特殊处理
if (cc && cc.sys && cc.sys.isNative) {
// 确保 XMLHttpRequest 存在
if (typeof XMLHttpRequest === 'undefined') {
defineGlobal('XMLHttpRequest', function() {
return cc.loader.getXMLHttpRequest();
});
}
// 确保 document 对象存在
if (typeof document === 'undefined') {
defineGlobal('document', {
createElement: () => ({ appendChild: () => {} }),
head: { appendChild: () => {} },
body: { appendChild: () => {} }
});
}
// 确保 location 对象存在
if (typeof location === 'undefined') {
defineGlobal('location', {
href: 'file://',
protocol: 'file:',
hostname: 'localhost',
host: 'localhost',
origin: 'file://'
});
}
console.log('[EnvFix] Native environment patched');
}
// 确保 require 函数存在
if (typeof globalObj.require === 'undefined') {
defineGlobal('require', function(module) {
if (globalObj.__modules && globalObj.__modules[module]) {
return globalObj.__modules[module];
}
console.warn(`[RequireFallback] Module '${module}' not found`);
return {};
});
}
})();
// ====== 引擎初始化保护系统 ======
const EngineReady = (function() {
let _promise = null;
let _resolve = null;
let _isReady = false;
let _checkInterval = null;
const safeCheckEngine = () => {
// 引擎已初始化
if (cc && cc.game && cc.game._isEngineInited) {
return true;
}
// 尝试监听初始化事件
if (cc && cc.game && cc.game.once) {
const eventName = cc.game.EVENT_ENGINE_INITED || 'engine-inited';
cc.game.once(eventName, () => {
_resolve && _resolve();
_isReady = true;
_checkInterval && clearInterval(_checkInterval);
});
return true;
}
return false;
};
return {
get isReady() { return _isReady; },
get promise() { return _promise; },
init() {
if (!_promise) {
_promise = new Promise(resolve => {
_resolve = () => {
_isReady = true;
resolve();
_checkInterval && clearInterval(_checkInterval);
};
// 首次检查
if (safeCheckEngine()) return;
// 轮询检查
_checkInterval = setInterval(() => {
safeCheckEngine() && _resolve();
}, 100);
});
}
return _promise;
},
safeAccess(callback) {
if (_isReady) {
try {
return callback();
} catch (e) {
console.error('[EngineSafe] Error:', e);
}
}
return _promise.then(callback).catch(e => {
console.error('[EngineSafe] Async error:', e);
});
}
};
})();
EngineReady.init();
// ====== 游戏主入口 ======
async function gameMainEntry() {
try {
console.log('[Main] Waiting for engine initialization...');
await EngineReady.promise;
console.log('[Main] Engine ready');
// 基本引擎配置
EngineReady.safeAccess(() => {
if (cc.view) {
cc.view.enableRetina(true);
cc.view.resizeWithBrowserSize(true);
cc.view.setDesignResolutionSize(960, 640, cc.ResolutionPolicy.SHOW_ALL);
}
});
// 加载SDK
await loadGravityEngineSDK();
// 加载启动场景
await loadStartScene();
} catch (error) {
console.error('[Main] Initialization failed:', error);
try {
cc.director.loadScene('start');
} catch (fallbackError) {
displayErrorFallback('启动失败\n请重启应用');
}
}
}
// 错误显示后备方案
function displayErrorFallback(message) {
try {
const errorDiv = document.createElement('div');
errorDiv.style.cssText = `
position: fixed;
top: 0; left: 0;
width: 100%; height: 100%;
background: black;
color: white;
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
font: 24px Arial, sans-serif;
text-align: center;
white-space: pre-line;
padding: 20px;
`;
errorDiv.textContent = message;
document.body.appendChild(errorDiv);
} catch (e) {
console.error('[Fallback] Display failed:', e);
}
}
// ====== SDK加载器增强版 ======
async function loadGravityEngineSDK() {
// 使用相对路径解决加载问题
const sdkPaths = [
'./assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js',
'_plugs/lib/gravityengine.mg.cocoscreator.min.js',
'lib/gravityengine.mg.cocoscreator.min.js'
];
for (const path of sdkPaths) {
try {
// 关键修复:在加载 SDK 前确保全局对象完整
ensureGlobalEnvironment();
// JSB 特殊处理:使用 require 加载
if (cc.sys.isNative && cc.sys.__globalAdapter?.require) {
cc.sys.__globalAdapter.require(path);
console.log('[SDK] Native require loaded:', path);
} else {
await loadScript(path);
console.log('[SDK] Loaded from:', path);
}
// 关键修复:加载后再次检查全局对象
ensureGlobalEnvironment();
initGravityEngine();
return;
} catch (e) {
console.warn('[SDK] Load failed:', path, e.message);
}
}
console.error('[SDK] All paths failed');
handleSDKLoadFailure();
}
function ensureGlobalEnvironment() {
// 获取全局对象
const getGlobalObject = () => {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof global !== 'undefined') return global;
if (typeof window !== 'undefined') return window;
if (typeof self !== 'undefined') return self;
return Function('return this')() || {};
};
const globalObj = getGlobalObject();
// 确保 self 在所有环境中都存在
if (typeof self === 'undefined') {
console.warn('[GlobalFix] self is undefined, patching...');
Object.defineProperty(globalObj, 'self', {
value: globalObj,
writable: true,
configurable: true,
enumerable: true
});
}
// 确保其他关键全局对象存在
const requiredGlobals = ['window', 'global', 'globalThis', 'document', 'location'];
requiredGlobals.forEach(name => {
if (typeof globalObj[name] === 'undefined') {
console.warn(`[GlobalFix] ${name} is undefined, patching...`);
Object.defineProperty(globalObj, name, {
value: globalObj,
writable: true,
configurable: true,
enumerable: true
});
}
});
// 原生平台特殊处理
if (cc && cc.sys && cc.sys.isNative) {
// 确保 location 对象存在
if (typeof location === 'undefined') {
Object.defineProperty(globalObj, 'location', {
value: {
href: 'file://',
protocol: 'file:',
hostname: 'localhost'
},
writable: false,
configurable: false,
enumerable: true
});
}
}
}
function loadScript(path) {
return new Promise((resolve, reject) => {
// 优先使用 Cocos 的加载系统
if (cc.assetManager?.loadScript) {
cc.assetManager.loadScript(path, (err) => {
if (err) {
// 原生平台特殊处理
if (cc.sys.isNative) {
console.warn('[SDK] Using native fallback for script loading');
try {
// 原生平台直接执行脚本
const jsb = cc.sys.__globalAdapter;
if (jsb && jsb.require) {
jsb.require(path);
return resolve();
}
} catch (nativeError) {
console.error('[SDK] Native require failed:', nativeError);
}
}
reject(err);
} else {
resolve();
}
});
return;
}
// 后备方案:直接创建 script 标签
try {
const script = document.createElement('script');
script.src = path;
script.onload = () => resolve();
script.onerror = () => reject(new Error(`Failed to load ${path}`));
document.head.appendChild(script);
console.warn('[SDK] Using DOM fallback for script loading');
} catch (e) {
reject(e);
}
});
}
function initGravityEngine() {
let GravityEngine = null;
// 1. 尝试标准方式获取
if (typeof GravityEngine === 'function') {
console.log('[SDK] GravityEngine found in local scope');
}
// 2. 尝试从全局对象中查找
else if (typeof window.GravityEngine === 'function') {
GravityEngine = window.GravityEngine;
console.warn('[SDK] Found GravityEngine in window object');
}
// 3. 尝试从其他全局对象中查找
else if (typeof global.GravityEngine === 'function') {
GravityEngine = global.GravityEngine;
console.warn('[SDK] Found GravityEngine in global object');
}
// 4. 尝试从 self 对象中查找
else if (typeof self.GravityEngine === 'function') {
GravityEngine = self.GravityEngine;
console.warn('[SDK] Found GravityEngine in self object');
}
// 5. 最后尝试从 globalThis 中查找
else if (typeof globalThis.GravityEngine === 'function') {
GravityEngine = globalThis.GravityEngine;
console.warn('[SDK] Found GravityEngine in globalThis object');
}
else {
console.error('[SDK] GravityEngine not found');
return;
}
try {
// 使用您的 AppID 624768904
GravityEngine.init({
appId: '624768904',
enableLog: true
});
console.log('[SDK] GravityEngine initialized with AppID 624768904');
} catch (e) {
console.error('[SDK] Init failed:', e);
}
}
function handleSDKLoadFailure() {
console.warn('[SDK] Using fallback analytics');
window.GravityEngine = {
init: () => console.warn('SDK unavailable'),
trackEvent: () => {}
};
}
// ====== 场景加载器 ======
async function loadStartScene() {
try {
// 加载主资源包
await new Promise((resolve) => {
if (!cc.assetManager?.loadBundle) {
console.warn('[Scene] AssetManager unavailable');
return resolve();
}
cc.assetManager.loadBundle('main', (err) => {
if (err) console.error('[Scene] Bundle load error:', err);
resolve();
});
});
// 加载场景
if (cc.director?.loadScene) {
cc.director.loadScene('start');
} else {
throw new Error('Director unavailable');
}
} catch (error) {
console.error('[Scene] Load failed:', error);
try {
cc.director.loadScene('start');
} catch (e) {
throw new Error('Fallback scene load failed');
}
}
}
// ====== UI_Entry组件 ======
const { ccclass, property } = cc._decorator;
@ccclass
export default class UI_Entry extends cc.Component {
@property(cc.ProgressBar)
progress_loading = null;
loginTimeoutHandler = null;
onLoad() {
EngineReady.safeAccess(() => {
try {
cc.director.getCollisionManager().enabled = true;
this._show();
} catch (e) {
console.error('[UI] onLoad error:', e);
this.startLoadGame();
}
}).catch(e => {
console.error('[UI] Engine access error:', e);
this.startLoadGame();
});
}
onDestroy() {
this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler);
}
async _show() {
this.progress_loading.progress = 0;
// 平台SDK初始化
if (cc.sys.isBrowser) {
try {
await this.initYPSDK();
} catch (e) {
console.error('[YPSDK] Init failed:', e);
this.startLoadGame();
}
} else {
this.startLoadGame();
}
// 登录超时保护
this.setLoginTimeout();
}
setLoginTimeout() {
if (cc.tween) {
this.loginTimeoutHandler = cc.tween(this)
.delay(10)
.call(() => {
console.warn('[Login] Timeout after 10s');
this.startLoadGame();
})
.start();
} else {
setTimeout(() => this.startLoadGame(), 10000);
}
}
async initYPSDK() {
if (typeof YPSDK === 'undefined') {
console.warn('[YPSDK] SDK unavailable');
return;
}
const config = {
gameChannelList: {
h5: { platformType: "h5", version: "1.0.0" },
tt: { platformType: "tt", appId: "tt09297f94961f881b02" },
wx: { platformType: "wx", appId: "wx6baaaa27ab5186ff" }
}
};
await YPSDK.init(39, "https://platform-shop-dev.hanyougame.com", config);
await YPSDK.login();
if (YPSDK.setLoginCallBack) {
YPSDK.setLoginCallBack(success => {
if (!success) return;
// 取消超时
this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler);
// 初始化分析SDK
if (r_GravityPlatform.default?.GA_Init) {
r_GravityPlatform.default.GA_Init(YPSDK.Platform.loginData.bindingId);
}
this.startLoadGame();
});
} else {
this.startLoadGame();
}
}
startLoadGame() {
const tasks = [
this._loadGameConfig,
this._loadRemoteConfig,
this._loadExcelData,
this._loadUserData,
this._loadCommonBundle,
this._loadMainBundle
].map(fn => fn.bind(this));
this.executeTasks(tasks, () => this._loadGame());
}
executeTasks(tasks, finalCallback) {
let completed = 0;
const total = tasks.length;
const runTask = async (index) => {
if (index >= total) {
finalCallback();
return;
}
try {
await tasks[index]();
completed++;
this._setProgress(completed / total);
runTask(index + 1);
} catch (e) {
console.error(`[Task ${index}] Failed:`, e);
completed++;
this._setProgress(completed / total);
runTask(index + 1); // 继续执行后续任务
}
};
runTask(0);
}
async _loadExcelData() {
if (!r_ExcelLoader?.ExcelLoader?.loadAll) {
console.warn('[Data] ExcelLoader unavailable');
return;
}
await r_ExcelLoader.ExcelLoader.loadAll();
console.log('[Data] Excel loaded');
}
async _loadGameConfig() {
if (!r_ResLoader.default?.loadRes) {
console.warn('[Config] ResLoader unavailable');
return;
}
const jsonAsset = await r_ResLoader.default.loadRes(
"resources",
"config/GameConfig",
cc.JsonAsset
);
if (jsonAsset && r_GameConfig.default) {
r_GameConfig.default.appConfig = jsonAsset.json;
jsonAsset.decRef && jsonAsset.decRef();
console.log('[Config] Game config loaded');
}
}
async _loadRemoteConfig() {
if (!r_GameConfig.default?.appConfig?.RemoteUrl) {
console.warn('[Config] RemoteUrl not set');
return;
}
const remoteUrl = r_GameConfig.default.appConfig.RemoteUrl;
const remotePath = cc.path.join(remoteUrl, "ADConfig.json");
try {
const remoteConfig = await r_ResLoader.default.loadRemote(remotePath, { ext: ".json" });
if (remoteConfig?.json && r_GravityPlatform.default) {
r_GravityPlatform.default.videoId = remoteConfig.json.ADUnitId[0];
r_GameConfig.default.adConfig = remoteConfig.json;
console.log('[Config] Remote config loaded');
}
} catch (e) {
console.error('[Config] Remote load failed:', e);
}
}
async _loadCommonBundle() {
if (!r_ResLoader.default?.loadBundle) {
console.warn('[Bundle] ResLoader unavailable');
return;
}
try {
await r_ResLoader.default.loadBundle(r_BundleConfig.BundleNames.Common);
console.log('[Bundle] Common loaded');
} catch (e) {
console.error('[Bundle] Common load failed:', e);
}
}
async _loadMainBundle() {
if (!r_ResLoader.default?.loadBundle) {
console.warn('[Bundle] ResLoader unavailable');
return;
}
try {
await r_ResLoader.default.loadBundle(r_BundleConfig.MainGameBundle);
console.log('[Bundle] Main loaded');
} catch (e) {
console.error('[Bundle] Main load failed:', e);
}
}
async _loadUserData() {
try {
// 音频初始化
r_AudioManager.AudioMgr?.init();
// 全局配置
r_GameGlobalVariable.GameGlobalVariable?.initPeiZhi();
// 网络检测
if (YPSDK?.Common?.curChannelData) {
const platformType = YPSDK.Common.curChannelData.platformType;
if (platformType === YPSDK.GamePlatformType.WX || platformType === YPSDK.GamePlatformType.TT) {
r_YpNetMag.YpNetMag?.failSever(() => {
r_YpNetMag.YpNetMag.isFail = true;
});
}
}
// 用户数据初始化
if (YPSDK?.Platform?.loginData) {
await r_YpNetMag.YpNetMag?.initServer(YPSDK.Platform.loginData);
}
} catch (e) {
console.error('[User] Load failed:', e);
}
}
_loadGame() {
try {
const guideIndex = r_PlayerDataManager.PlayerDataMgr.GetGuideIndexByTaskName(
r_Const_Common.GuideName.战斗背包
);
if (guideIndex !== r_Const_Common.GameBagGuideIndex.引导完结) {
// 新玩家流程
r_PlayerDataManager.PlayerDataMgr.GMSetGuideIndex?.(
r_Const_Common.GuideName.战斗背包,
r_Const_Common.GameBagGuideIndex.引导初始1
);
r_GameDataManager.GameDataMgr?.ClearGameBagData();
r_GameGlobalVariable.GameGlobalVariable.nowlevel = 1;
r_UIManager.default?.open(
r_BundleConfig.BundleNames.Game,
r_UIConfig_Game.UIView_Game.UI_GameView
);
} else {
// 老玩家流程
r_EventManager.EventMgr?.dispatchEvent(r_EvenType.EVENT_TYPE.Game_Load_View, true);
r_UIManager.default?.open(
r_BundleConfig.BundleNames.Home,
r_UIConfig_Home.UIView_Home.UI_Hall
);
}
// 白名单检查
this.checkWhiteList();
} catch (e) {
console.error('[Game] Load failed:', e);
try {
cc.director.loadScene('start');
} catch (sceneError) {
console.error('[Game] Scene load failed:', sceneError);
}
}
}
async checkWhiteList() {
try {
if (!YPSDK?.Platform?.loginData || !YPSDK.platformUrl) return;
const url = `${YPSDK.platformUrl}/User/GetCfgData?userId=${YPSDK.Platform.loginData.userUid}&keyId=NoVideo`;
if (r_HttpManager.HttpMgr?.requestData) {
r_HttpManager.HttpMgr.requestData(res => {
if (res?.data?.keyData === "true") {
r_PlayerDataManager.PlayerDataMgr.WHITE_NAME_NO_VIDEO = true;
}
}, url);
}
} catch (e) {
console.error('[WhiteList] Check failed:', e);
}
}
_setProgress(progress) {
if (!this.progress_loading) return;
this.progress_loading.progress = Math.max(0, Math.min(1, progress));
}
}
// ====== 启动游戏 ======
if (cc?.game?.run) {
cc.game.run(() => {
// 确保环境修复完成
ensureGlobalEnvironment();
gameMainEntry();
});
} else {
setTimeout(() => {
ensureGlobalEnvironment();
gameMainEntry();
}, 1000);
}
```
### 关键修复点
1. **JSB 引擎特殊处理**:
```javascript
// JSB 特殊处理:使用 require 加载
if (cc.sys.isNative && cc.sys.__globalAdapter?.require) {
cc.sys.__globalAdapter.require(path);
console.log('[SDK] Native require loaded:', path);
} else {
await loadScript(path);
console.log('[SDK] Loaded from:', path);
}
```
在 Cocos Creator 原生环境中,必须使用 `cc.sys.__globalAdapter.require` 来加载脚本,而不是标准的 `cc.assetManager.loadScript`。
2. **增强的全局对象修复**:
```javascript
// 确保 self 在所有环境中都存在
if (typeof self === 'undefined') {
console.warn('[GlobalFix] self is undefined, patching...');
Object.defineProperty(globalObj, 'self', {
value: globalObj,
writable: true,
configurable: true,
enumerable: true
});
}
```
在 SDK 加载前强制定义 `self` 对象,确保 SDK 内部不会出现引用错误。
3. **启动流程优化**:
```javascript
cc.game.run(() => {
// 确保环境修复完成
ensureGlobalEnvironment();
gameMainEntry();
});
```
在游戏启动时立即执行环境修复,确保所有全局对象在引擎初始化前就已定义。
### 额外修复步骤
1. **修改重力引擎 SDK 文件**(可选但推荐):
在 `gravityengine.mg.cocoscreator.min.js` 文件开头添加:
```javascript
// 在重力引擎 SDK 文件开头添加
(function(global) {
if (typeof self === 'undefined') {
global.self = global;
}
})((function() {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof global !== 'undefined') return global;
if (typeof window !== 'undefined') return window;
return Function('return this')() || {};
})());
```
2. **清理构建缓存**:
```bash
# Windows
rmdir /s /q build
rmdir /s /q temp
rmdir /s /q library
# macOS/Linux
rm -rf build/ temp/ library/
```
3. **构建设置**:
在 Cocos Creator 构建面板中:
- 确保 "MD5 Cache" 选项已启用
- 在 "Native" 选项卡中,勾选 "Debug" 以获取更多日志
- 设置 "Script Debugging" 为 "Both"
### 错误分析
错误日志显示:
```
ERROR: Uncaught ReferenceError: self is not defined, location: src/assets/_plugs/lib/gravityengine.mg.cocoscreator.min.dbb97.js:0:0
```
原因分析:
1. 在 Cocos Creator 原生环境中,`self` 对象默认不存在
2. 重力引擎 SDK 内部使用了 `self` 对象
3. 之前的修复代码执行时机可能太晚,在 SDK 加载时环境尚未准备好
4. JSB 引擎的脚本加载机制与浏览器环境不同
### 测试验证
1. 在 Android 设备上安装应用
2. 检查日志中是否出现以下关键消息:
```
[SDK] Native require loaded: ./assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js
[SDK] GravityEngine initialized with AppID 624768904
```
3. 确认不再出现 `self is not defined` 错误
阅读全文
相关推荐


















