模拟手机环境

在大多数情况下, 编辑器中运行和手机中运行的效果是一样的, 不过有些时候我们需要用到手机与Lua的通信功能. 这样会造成我们需要测试与手机交互就需要到手机端运行, 没有达到预期效果并不能快速准确的定位到错误, 所以我们总结出一些经验.

在点击编辑器运行游戏按钮的时候, 实际上加载的是工程目录下editor_start.lua脚本, 这个脚本也只会在编辑器下加载, 在手机环境中运行通常会加载app.lua脚本, 所以我们就可以在editor_start.lua脚本中做一些模拟手机环境的操作, 以及可以方便的区分是否是编辑器.

1. 模拟与原生环境通信

在editor_start.lua中重写xe.ScriptBridge:call()方法, 这个是Lua与原生环境通信的Bridge接口.

---模拟同步方法
function xe.ScriptBridge:call(handler, action, message)
    local _handler = __EditorHandler[handler]
    if _handler == nil then
        return nil
    end
    lcoal _action = _handler[action]
    if _action == nil then
        return nil
    end
    return action(message)
end
---模拟异步方法
function xe.ScriptBridge:callAsync(handler, action, message, callback)
    local _handler = __EditorHandler[handler]
    if _handler == nil then
        return
    end
    lcoal _action = _handler[action]
    if _action == nil then
        return
    end
    action(message, callback)
end
---创建模拟Handler
__EditorHandler = {}
__EditorHandler.HandlerName = {}
function __EditorHandler.HandlerName.ActionName(msg)
    print(msg)
end

在上边写完模拟脚本之后, 我们可以调用试一下

    xe.ScriptBridge:call("HandlerName", "ActionName", "Show Msg")

运行结果如下:

2020-07-16 15:51:43.455 [LUA][PRINT]   ✍️✍️✍️ @:/Asset/editor_start.lua<45>    Show Msg

2. 其他注意事项

  1. 在Windows下运行时, 对于路径是大小写不敏感的, 所以在require脚本的时候不需要区分大小写, 但是在手机端是大小写敏感的, 所以这里一定要注意require脚本的时候一定要注意大小写拼写问题.
@Copyright © cosmos 2019 all right reserved,powered by Gitbook修订时间: 2021-04-12 18:28:14

results matching ""

    No results matching ""