1

I am coding in Unity using C# and developing for WebGL. I need to use browser JavaScript so have written a .jslib from which I call methods in C# using Marshalling.

Is it possible for me to set a JavaScript callback to a C# Action, Func, or Event Handler like so:

// Javascript in .jslib called from C# using static extern
// action being the C# method that I want to call
// On callback I get -> TypeError: action is not a function
SetOnOpen: function (action) {
    $jsobj.onopen = function () {
        action();
    };
},

I've tried each of these, but don't appear to be doing it properly. I know that C++ can call C# functions, but JavaScript must communicate differently somehow.

Attempts:

[DllImport("__Internal")]
private static extern void SetOnOpen(ref OnOpenHandler handler);

[DllImport("__Internal")]
private static extern void SetOnOpen(ref Action action);

[DllImport("__Internal")]
private static extern void SetOnOpen(IntPtr handler);

No matter what I try, I get a TypeError stating that the object that I'm passing over to the JavaScript isn't a function. I've tried:

  • Using Action and Event Delegates
  • Using ref, IntPtr, and neither

Anyone know if this is even possible? Like I said, I successfully called a C# method in a C++ .dll before, so figured it would be possible to do so from a .jslib.

gman
  • 100,619
  • 31
  • 269
  • 393
sk84z
  • 193
  • 1
  • 3
  • 10
  • [Is this answer helpful?](http://stackoverflow.com/questions/35183253/unity3d-upload-a-image-from-pc-memory-to-webgl-app) – gman Aug 05 '16 at 04:43

1 Answers1

0

From my experience, the only way to make the two communicate is by SendMessage. If you need to carry over multiple parameters, you can attach an array.

  • Thanks for the reply! I wanted to avoid the GameObject.Find() and Reflection calls. :( I ended up just emulating Unity's example in Simple WebSockets for WebGL and using an Enumerator which constantly checks for new messages. Not the prettiest, but it's more efficient than send message and works quite well. :) – sk84z Aug 05 '16 at 20:13