When you build a WebGL app from Unity and use the test HTML sample code to embed the page, it starts immediately.
If you want your app for an event before launching the app, here’s an example of hosting the app with a stand-in placeholder image – where the user must click the image before the app loads.
<script src="/blog/content/WebHalt/TemplateData/UnityProgress.js"></script> <script src="/blog/content/WebHalt/Build/UnityLoader.js"></script> <script> // Called to replace the proxy image with the app. // Or more specifically, it starts the app behind the image, and deletes the image. function StartImg() { // Call the Unity WebGL initialization. UnityLoader.instantiate("game", "/blog/content/WebHalt/Build/WebHalt.json", {onProgress: UnityProgress}); // The image does not need to be deleted by hand. The initialization // function will automatically clear out the insides of the <div> // used to contain the app. } </script> <div class="webgl-content"> <div id="game" style="width: 960px; height: 600px"> <img src="/blog/content/WebGLPlaceholder.png" onclick="StartImg()"> </div> </div>
Note that delaying the instantiation also delays the process of downloading the application.
Try the example below. Click on the image.
It’s pretty simple. First, there’s an image (WebGLPlaceholder.png) that’s placed inside the div used to contain the Unity app. It’s made to be the exact same dimensions as the app. The app also doesn’t instantly start, but initialization code is placed inside a function that is called when the proxy image is clicked on.
The function could have just as easily been made inline. Example in the snippet below.
<!–– An example of the programming for onclick being inline. ––> <div class="webgl-content"> <div id="game" style="width: 960px; height: 600px"> <img src="/blog/content/WebGLPlaceholder.png" onclick="UnityLoader.instantiate('game', '/blog/content/WebHalt/Build/WebHalt.json', {onProgress: UnityProgress});"> </div> </div>
As it mentions in the source of the first snippet’s comments, removal of the image does not need to be handled. The initialization for the Unity web app will clear out anything inside of the app’s div container for you.
It’s as simple as that!
Information on the sample WebGL app can be found here.
Built with Unity 2018.3.8f1
– Stay strong, code on. William Leu
More articles here. More articles about Unity WebGL here.