This means only the function “createUnityInstance” will now be visible as global, and you need to instantiate your own “unityInstance” variable with it. Also note it now requires the canvas object to be passed instead of the id.
Thank you. But how exactly do I instantiate with createUnityInstance? I tried to put a “var unityInstance =” infront of it in the index.html. but then it reports sendMessage is not a function.
It’s usually a good idea to log the objects you’re creating when you’re exploring. Try putting in a “console.log(unityInstance)”. I believe it’s either under the Module object, or it should be capitalised as “SendMessage”. Just log it in the console and explore the object, you should see it somewhere in there.
Here is the log, and I did
var unityInstance = createUnityInstance…
console.log(unityInstance)
Please help, I don’t understand, I see SendMessage right there, and I tried “SendMessage” with captial S, doesn’t work either.
createUnityInstance now returns a Promise, you need to add “.then((unityInstance) => {… do something with it …})” after it and continue a chain from there. More info on promises can be found here: JavaScript Promises: an introduction | Articles | web.dev.
The reason you’re seeing the object function, but it says undefined when logging is because promises do not resolve immediately. If you log the variable immediately after the promise, it will be undefined as the Promise has not resolved yet. It will show up in the console, but with a small “i” next to it which will indicate the browser “filled it in when it eventually became available afterwards”. It’s a useful browser feature which can surely trip you up if you don’t understand how promises work.
There is an easy solution.
It’s a matter of storing the unityInstance object in a window variable that you can latter use. The best moment to do that is right after the onload gets set, at the beginning of the “then”. So:
script.onload = () => {
window.gameInstance = createUnityInstance(canvas, config, (progress) => {
progressBarFull.style.width = 100 * progress + "%";
}).then((unityInstance) => {
window.gameInstance = unityInstance; //This is where you store the object
loadingBar.style.display = "none";
fullscreenButton.onclick = () => {
unityInstance.SetFullscreen(1);
};
You can then send messages at a later time with
gameInstance.SendMessage(GameObject_name, Method_name,value)
You can even use this variable inside the .jslib plugins. So that events that respond to the changes in the browser may interact with objects inside the unityInstance object.