JavaScript SendMessage not working with default WebGL build in 2019.4.12

Hi All,
I’ve found a bug with the default WebGL build in 2019.4.12.

The html generated doesn’t create a unityInstance variable when it calls UnityLoader.instantiate

so then if you try to call SendMessage using the code in the documentation

unityInstance.SendMessage(objectName, methodName, value);

if won’t work because the unityInstance variable hasn’t been defined

It’s possible to fix this by editing the html code
change

UnityLoader.instantiate("unityContainer", "Build/prototype.json");
</script>```

to 

```<script>
var unityInstance = UnityLoader.instantiate("unityContainer", "Build/prototype.json");
</script>```

Shouldn't this be part of the exported HTML though, as it will get overwritten every build?

It is possible to use a custom WebGL template to control the kind of output that is generated in index.html.

We could change the default template to do that, but in 2020.1 the code has further changed, and unityInstance is received as a result to a Promise returned by createUnityInstance() function. The idea here is generally to avoid littering the global JS scope with variables, which is considered bad practice, but instead leave it to the programmer to manage the variables in the global scope that are needed. That way developers can control the names that their web pages have in the global namespace, and avoid collisions (e.g. if running two Unity game instances on the same page)

1 Like

Thanks for explaining the reasoning behind this and the heads-up on the custom template, I’ll look into writing one of them.

With regards to the default template would it be useful to add an export option that switches the JavaScript functionality on? Might be helpful for users with little HTML/JS experience.

Thanks, that is an interesting suggestion. Not sure if it would be worth the added complexity. We’ll take this into consideration. Btw, which doc page were you reading about the SendMessage?

Maybe you could just add to the documentation that this step is needed if you are using the default template.

I looked at a couple of tutorials on youtube as well and they didn’t seem to have any problems, and I noticed that the code in the example on the custom templates page (Unity - Manual: WebGL templates) has the variable assignment in it even though it says it’s the code used for the minimal template.

Has the template been changed recently?