cocos creator调用远程文本,做函数来执行。

主要调用这2个函数。
// 原生
if (window.jsb && jsb.evalString) { jsb.evalString(codeStr); }
// Web
else { new Function(codeStr)(); }

const { ccclass, property } = cc._decorator;

@ccclass
export default class Scene2413 extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;


    onLoad() { }

    start() {

    }

    cbBtn() {
        let strcode =
        `
        // 简单导出一个函数到全局,方便上面调用
        window.remoteAdd = function (a, b) {
            return a + b;
        };

        // 你也可以 export 一个类、一个组件,甚至直接 cc.Class({...}) 注册新组件
        console.log('[Remote] 远程代码已加载 ok');
        `
        this.runCode(strcode);
    }

    runCode(codeStr: string) {
        if (window.jsb && jsb.evalString) {
            /* ---------- 原生端 ---------- */
            jsb.evalString(codeStr);
            cc.log('[RemoteCode] 原生 jsb.evalString 完成');
        } else {
            /* ---------- Web / 小游戏 ---------- */
            try {
                // 产生一个虚拟文件名,方便调试
                // const virtualName = 'remote_main.js';
                // const wrapped = `(function(){\n${code}\n});\n//# sourceURL=${virtualName}`;
                // const fn = new Function('return ' + wrapped)(); // 立即拿到 IIFE
                // fn();
                // cc.log('[RemoteCode] Web eval 完成');
                new Function(codeStr)();
                console.log('fun use:', window.remoteAdd(1, 2))
                this.label.string = 'remoteAdd(1,2)=' + window.remoteAdd(1, 2);
            } catch (e) {
                cc.error('[RemoteCode] Web 执行失败', e);
            }
        }
    }

    // update (dt) {}
}

标签: none

添加新评论