javascript - 从 Unity 中调用浏览器上的 javascript 字符串函数返回 null

标签 javascript unity-game-engine unity-webgl

我有一个 WebGL unity 项目,它尝试在浏览器上执行 javascript 代码并返回一个值。

我的 Assets/Plugins/WebGL 文件夹中有以下 .jslib 文件:

var BrowserPlugin = {
    GetEndpointURL: function()
    {
        var endpoint = window.itd.getEndpointUrl();

        console.log("endpoint: " + endpoint);

        return endpoint;
     }
};

mergeInto(LibraryManager.library, BrowserPlugin);

在我的 Unity C# 代码中,我导入 dll 并调用我的 javascript 方法,如下所示:

[DllImport("__Internal")]
private static extern string GetEndpointURL();

string endpointURL = GetEndpointURL();

问题是,在我的 C# 代码中,endpointUrl 变量始终为 null。但是,在我的浏览器控制台中,我可以清楚地看到在返回之前正确的值已记录在浏览器 JavaScript 中。是什么导致该值恢复为空?

最佳答案

这是您的代码:

GetEndpointURL: function()
{
    var endpoint = window.itd.getEndpointUrl();
    console.log("endpoint: " + endpoint);
    return endpoint;
}

不能直接返回字符串(端点)。您必须创建一个缓冲区来保存该字符串,此过程包括使用 _malloc 分配内存,并使用 writeStringToMemory 将旧字符串复制到新的内存位置。

GetEndpointURL: function()
{
    var endpoint = window.itd.getEndpointUrl();
    console.log("endpoint: " + endpoint);

    var buffer = _malloc(lengthBytesUTF8(endpoint) + 1);
    writeStringToMemory(endpoint, buffer);
    return buffer;
}

关于javascript - 从 Unity 中调用浏览器上的 javascript 字符串函数返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654228/

相关文章:

javascript - 未处理的拒绝(类型错误): Cannot read property 'map' of undefined

azure - 在 Azure 网站上托管 Unity3D 游戏

ios - 使用 Storyboard自定义 Unity3D Xcode 项目

javascript - 如何从浏览器中删除统一堆内存?

c# - 在 Unity3d 中构建 WebGL 的 HTTPS 客户端

javascript - 如何检测元素外的点击?

javascript - 如何调试 assemble.io(最好在 Chrome 控制台中)

javascript - 如何从样式化组件 (React) 访问 CSS 值?

unity-game-engine - 如何在unity Netcode中为GameObject使用ClientRpc(或ServerRpc)?

http - 使用 UnityWebRequest 的响应代码为 0 的通用/未知 HTTP 错误