I’m trying to join an ASP.NET Core website, Web API and Unity project together. I developed them as separate projects for faster development but now it’s time to embed the Unity project into a page in the website.
I’m trying to fetch a hidden field on the page that has some data which the Unity project will need to get data to and from from the API.
I have a very small piece of Javascript for this. For testing, I’ve added an alert dialog that shows me the data that’s been fetched from the page. When I call it, the alert pops up and shows the correct data. However, the string containing the data isn’t being passed to the C# method that’s calling it.
This is what I have:
[DllImport("__Internal")]
private static extern string UserInfo();
void Start()
{
TestJS();
SetupEventHandlers();
Initialize();
}
private void TestJS()
{
var test = UserInfo();
Debug.Log("User Info = " + test);
}
I’m no Javascript expert and so was surprised there was no return type, judging by the examples on the Unity docs, so this appears to be correct. ‘unity-hidden’ is the hidden field on the page. And like I said, it’s fetching the value for the alert but doesn’t seem to be returning the value back to the code in TestJS() as ‘test’ is empty when I try to output the value to Debug.Log (I’m using a third party control that shows a debug overlay on my Unity project).
The documentation has several examples over here for javascript interaction in the browser. Your Unity / C# / C++ code is actually run in a virtual machine which has it’s own managed emulated memory inside the browsers javascript. Since you want to get an actual C# string, you have to allocate it on the managed heap. See the example method “StringReturnValueFunction”.
Note that the exact approach has changed several times over the years. So it might depend on what Unity version you’re using. Here’s an SO question about returning a string from a jslib. The answer actually has two approaches (one old, one new).