从Unity调用浏览器上的javascript字符串函数返回null [英] Calling javascript string function on browser from Unity returns null

查看:179
本文介绍了从Unity调用浏览器上的javascript字符串函数返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a WebGL unity project which attempts to execute javascript code on the browser and return a value.

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

I have the following .jslib file in my Assets/Plugins/WebGL folder:

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

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

        return endpoint;
     }
};

mergeInto(LibraryManager.library, BrowserPlugin);

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

In my c# code in unity, I import the dll and call my javascript method like so:

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

string endpointURL = GetEndpointURL();

问题是,在我的c#代码中 endpointUrl 变量始终为null。但是,在我的浏览器控制台中,我可以清楚地看到在返回之前在浏览器javascript中记录了正确的值。是什么导致这个值回到统一为null?

The problem is, in my c# code the endpointUrl variable is always null. However, in my browser console, I can clearly see the correct value is logged in the browser javascript before I return it. What is causing this value to come back to unity as null?

推荐答案

这是你的代码:

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

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

You cannot return string (endpoint) directly. You have to create a buffer to hold that string and this process includes allocating memory with _malloc and copying old string to that new memory location with writeStringToMemory.

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

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

这篇关于从Unity调用浏览器上的javascript字符串函数返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆