How can I check or receive a message when the a Unity WebGL app is finished with loading and ready for use? What I want is to run a JavaScript function of my Webinterface after the WebGL App is ready.
If you're looking into using a front-end framework, you might want to look into this library I've made. It adds functionality for two way communication between your webpage and Unity content. To send messages from your Unity content, back to the web page, you can create JavaScript listeners which can be triggered from your CSharp code, and even pass data.
// Create a new Unity Content object (using the library)
this.unityContent = new UnityContent(
"MyGame/Build.json",
"MyGame/UnityLoader.js" );
// Then add a new listener to the object.
this.unityContent.on("GameOver", score => {
// Do somehting...
});
In order to trigger the event we've just created, you have to create a JSLib file to bind the communication. The listener registered in React is now available in the ReactUnityWebGL object in any JSLib file. You can now create a JSLib file and get started. We're going to create a new JSLib file in the following directory. Assets/Plugins/WebGL/MyPlugin.jslib.
mergeInto(LibraryManager.library, {
// Create a new function with the same name as
// the event listeners name and make sure the
// parameters match as well.
GameOver: function(score) {
// Within the function we're going to trigger
// the event within the ReactUnityWebGL object
// which is exposed by the library to the window.
ReactUnityWebGL.GameOver(score);
}
});
Finally, to trigger to event within your CSharp code. We have to import the JSLib as following.
using UnityEngine;
public class GameController : MonoBehaviour {
// Import the JSLib as following. Make sure the
// names match with the JSLib file we've just created.
[DllImport("__Internal")]
private static extern void GameOver (int score);
// Then create a function that is going to trigger
// the imported function from our JSLib.
public void GameOver (int score) {
GameOver (score);
}
}
I use a different approach. This is especially helpful because you can define callbacks in whatever part of your Unity code you wish i.e. you can react to async events.
//in your html|js
function OnAppReady(){
console.log("### application is loaded")
}
//in Unity
void Start()
{
//js callback when application is loaded
Application.ExternalEval("OnAppReady()");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With