JavaScript与Unity交互之——接参
用法:
// 定义接收参数的方法 该方法名需与U3D开发人员同步
getUidFromU3d(uid) {
console.log(uid);
}
// 类似依赖注入
getUidFromU3d.inject(window.InvokeFunc);
/**
* 伪代码 入参为:方法名 参数
* 由U3D调用
* 也可在浏览器开发者工具中进行调用测试
*/
window.InvokeFunc('getUidFromU3d', uid);
源代码:
// 依赖注入
Function.prototype.inject = function (injectFunc) {
try {
var _funcName = this.name.replace('bound ', '');
var _injectFuncName = injectFunc.name.replace('bound ', '');
window['reflectionFunc_' + _funcName] = this;
eval(
'window[_injectFuncName] = function _injectFuncName(funcName, args) {\n' +
'return eval("reflectionFunc_" + funcName + "(args);")\n' +
'}'
);
return true;
} catch (error) {
console.log('Reflection injected function failed,check the params.');
return false;
}
};
// 依赖释放
Function.prototype.release = function () {
try {
var _funcName = this.name.replace('bound ', '');
return delete window['reflectionFunc_' + _funcName];
} catch (error) {
console.log(
'Reflection release failed,Please ensure that the method has been injected'
);
return false;
}
};
function InvokeFunc(funName, funParams) {}