Calling Unity WebGL Methods from Javascript

marcosecchi Tutorials, Unity3D 0 Comments

Lately I’ve been working on a Unity3D WebGL application and one of the client’s requests was to load a configuration file at startup.

Usually this means the client has no idea where and when this file will be published (i.e.: no hard coding), so the best way to solve this is to pass the url from the HTML wrapper.

Calling a Unity Method from Javascript

The easiest solution is to use Javascript: Unity lets you use the SendMessage() method (the WebPlayer plugin had u.getUnity().SendMessage()):

SendMessage ("aGameObject", "aMethod", "aParameter");

The aGameObject parameter is a GameObject in the scene including the method (you’ll have to add the full hierarchy path in case it has one or more parents). The example below shows a game object with a single parent:

"aParentGameObject/aGameObject"

The aParameter parameter is a single string value that will be passed as a parameter for aMethod.

  If there are no parameters in the function you’ll have to pass an empty string.

Waiting for the Application Load

There’s a small caveat… if the WebGL application hasn’t been fully loaded, an error will be raised: in my case this will happen all the times as I need the parameter immediately.

The best solution is to request the method call directly from Unity (for instance, from a MonoBehavior Start()): just use the Application.ExternalEval() function, that executes a Javascript available in the HTML wrapper.

Just to be clear, here’s what’s happening:

  1. the Unity application starts and calls a Javascript method in the HTML wrapper
  2. Javascript retrieves the needed parameter
  3. Javascript calls a Unity method, passing the parameter

Example

In my applicationHTML, I’ve added the following Javascript code:

that logs some message in the console, calls the SetAppInitUrl() method to a gameobject called AppController.

The called gameobject will have this script attached:

As you can see, it’s calling the Javascript function and exposes the SetAppInitUrl() method for the callback.

Improving Things

As you’ll have noticed, this kind of messaging is dependent on strings that may change (I’m used to rename things in the scene a lot…).

as a solution, you can pass the gameobject name directly from Unity. For instance:

and

  As a nicer solution, you can always pass the full gameobject path.