C# and WebGL Interaction

Hi all,

I have a Object in Web Browser Javascript - WebGL:

var data = {
            username: "User1",
            message: "Este es User1"
        }

and i need to pass this to C# Unity:

SendMessage ('MyGameObject', 'MyFunction', data);

How can get with C# from unity?.

Hi,

found something after googling a bit.

Couldn’t you just do something like that?

SendMessage ('MyGameObject', 'MyFunction', data.username);

Method in your GameObject Script:

public void MyFunction(String str)
{
    //do something with str
}

You can send the whole object as a string to c# function.
The c# function parameter data type will be string and will recieve
like:"{"username":"name","message":"value"}

In short converting javascript object into json string and parsing it back in c#

If you want to pass it straight to a C# function, you need to marshal it somehow. You can either marshal it as an object, and have a C# struct with the same layout that gets filled in, or you can pass the two elements as separate string parameters to the same function. Either way, to do this you need to use direct C# method calls from the Javascript, rather than SendMessage, and it requires some care.

Using SendMessage with JSON.stringify(data) is certainly easier, if you have the ability to parse the JSON from C# and don’t mind the latency of SendMessage. If you think about it though, there’s a crazy amount of inefficiency here.

Another approach that might work is to pull the data from C# instead of pushing it from Javascript. e.g. bind emscripten_run_script_string and use that:

[DllImport("__Internal")]
extern static string emscripten_run_script_string(string script);

...

string username = emscripten_run_script_string("data.username");
string message = emscripten_run_script_string("data.message");

I think this should work in theory, but I haven’t tried it. Obviously it requires “data” to be a javascript global - if it’s not, you need to change the script code to some other way of accessing the data.