Unity WebGL JavaScript interaction

A note-to-ourselves…

This one just somehow extends the official WebGL Interacting with Browser Scripts documentation from Unity. So it’s really more a note-to-ourselves which contains a few notes we have to look up from time to time again. So we decided to just pin them down.

As an example for WebGL-JavaScript-C# communication, we are using an extract from the Kongregate API Wrapper that returns the Kongregate username back to Unity, but it can easily be changed and used as a template for other similar purposes, too.

Creating the .jslib

As in Unity the file extension .js is already used by Unity Script files (we are using C# btw), we created a new text file with the .jslib extension (e.g. with Notepad++) and put it into our Unity project Assets/Plugins subfolder.

Code annotations:

  • the $ClassVar (2) is empty but could be used if we need to store something inside the class.
  • SubmitStat (3) receives a string as a parameter which needs to be converted before use.
  • in SubmitStat we find the SendMessage(GameObjectName, Functionname, Parameter) call (6).
  • GetKongUserName (9) returns the string to Unity. Therefore it has to be buffered.
  • in order to make this work, don’t forget to assign the dependencies, see autoAddDeps line (17).
  • for logging, we use console.log, which is similar to C# Debug.Log (appears in the browser web console).

Accessing the .jslib

In order to communicate with the functions in the library, we added a Game Object Kongregate Manager in Unity (the same name as specified in the SendMessage function, line 6) that holds the script that communicates with the .jslib.

Code annotations:

  • don’t forget to define the using statement System.Runtime.InteropServices; (1)
  • to maintain the ability to test the scene in Unity Editor, we provided the compiler directives (3), returning a fake result in editor mode (8).
  • we call the external JavaScript functions, surrounding our WebGL build.

That’s it, no big magic as mentioned above, just some notes-to-ourselves

Your Fantasy Arts Team

Share on FacebookShare on Google+Tweet about this on TwitterShare on TumblrShare on LinkedInEmail this to someone

Leave a comment

Your email address will not be published.