Version: 2019.4
WebGL: Interacting with browser scripting
Bloqueo del cursor y modo de pantalla completa en WebGL

Utilizando plantillas WebGL

When you build a WebGL project, Unity embeds the player in an HTML page so that it can be played in the browser. The default page is a simple white page with a loading bar on a grey canvas. Alternatively, you can select a minimal template (with only the necessary boilerplate code to run the WebGL content) in the Player settings (menu: Edit > Project Settings, then select the Player category).

The built-in HTML pages are fine for testing and demonstrating a minimal Player, but for production purposes, it is often good to see the Player hosted in the page where it will eventually be deployed. For example, if the Unity content interacts with other elements in the page via the external call interface then it must be tested with a page that provides those interacting elements. Unity allows you to supply your own pages to host the Player by using WebGL templates.

Estructura de una Plantilla WebGL

Las plantillas personalizadas se agregan a un proyecto al crear una carpeta llamada “WebGLTemplates” en la carpeta Assets - las plantillas en sí son sub-carpetas dentro de esta carpeta. Cada carpeta de planilla contiene un archivo “index.html” con cualquier otro recurso que la página necesite, tal como imágenes u hojas de estilo.

Once created, the template appears among the options on the Player settings. The name of the template is the same as its folder. Optionally, the folder can contain a file named thumbnail.png, which should have dimensions of 128x128 pixels. The thumbnail image is displayed in the inspector to hint at what the finished page will look like.

El archivo html necesita tener al menos estos siguientes elementos:

  • Una etiqueta script del Unity WebGL loader: <script src="%UNITY_WEBGL_LOADER_URL%"></script>

  • Script for instantiating Unity: <script> var unityInstance = UnityLoader.instantiate("unityContainer", "%UNITY_WEBGL_BUILD_URL%");</script>

  • A <div> tag, which has an id that is used in the instantiation function. The contents of this div will be replaced with the Unity instance.

UnityLoader.instantiate(container, url, override)

UnityLoader.instantiate es responsable de crear una nueva instancia de su contenido.

  • container can be either a DOM element (normally a <div> element) or an id of a DOM element. If the DOM element is provided, then the Unity runtime will be instantiated immediately. If an id of a DOM element is provided, then the Unity runtime will be instantiated after the whole document is parsed (which means you can provide an id of a DOM element which has not yet been created at the time of UnityLoader.instantiate() call).

  • url especifica la dirección del archivo json, que contiene información sobre la construcción (puede usar la variable %UNITY_WEBGL_BUILD_URL% que se resolverá automáticamente en el momento de la construcción).

  • override is an optional parameter which can be used to override the default properties of the instance. For example, you can override the compatibilityCheck, onProgress and popup functions, as those are properties of the instance. Note that Module is a property of the instance as well, so the properties of the Module can be overridden at instantiation time too. Consider the following example:

UnityLoader.instantiate("MyContainer", "%UNITY_WEBGL_BUILD_URL%", {
  compatibilityCheck: function (unityInstance, onsuccess, onerror) {
    if (!UnityLoader.SystemInfo.hasWebGL) {
      unityInstance.popup("Your browser does not support WebGL",
        [{text: "OK", callback: onerror}]);
    } else if ( {
      unityInstance.popup("Please note that Unity WebGL is not currently supported on mobiles. Press OK if you wish to continue anyway.",
        [{text: "OK", callback: onsuccess}]);
    } else if (["Edge", "Firefox", "Chrome", "Safari"].indexOf(UnityLoader.SystemInfo.browser) == -1) {
      unityInstance.popup("Please note that your browser is not currently supported for this Unity WebGL content. Press OK if you wish to continue anyway.",
        [{text: "OK", callback: onsuccess}]);
    } else {
  onProgress: MyProgressFunction,
  Module: {
    onRuntimeInitialized: MyInitializationCallbackFunction,

Template tags

During the build process, Unity looks for special tag strings in the page text and replaces them with values supplied by the Editor. These include the name, onscreen dimensions and other useful information about the player.

Tags are delimited by percent signs (%) in the page source. For example, if the product name is defined as MyPlayer in the Player settings:


… en el archivo index de la plantilla será remplazada con


…in the host page generated for the build. The complete set of tags is given below:

  • UNITY_WEB_NAME: Nombre del player.

  • UNITY_WEBGL_LOADER_URL: URL of the UnityLoader.js script, which performs instantiation of the build.

  • UNITY_WEBGL_BUILD_URL: URL of the JSON file, containing all the necessary information about the build.

  • UNITY_WIDTH y__UNITY_HEIGHT__:Ancho y alto en pantalla del jugador en píxeles.

  • UNITY_CUSTOM_SOME_TAG: If you add a tag to the index file in the form UNITY_CUSTOM_XXX, then this tag will appear in the Player settings when your template is selected. For example, if you add &lt;title&gt;Unity Player | %UNITY_CUSTOM_MYTAG%&lt;/title&gt; to the source, the Player settings look like this:

The textbox next to the tag’s name contains the text that the custom tag will be replaced with during the build.


Para ilustrar el uso de la etiquetas de plantilla, aquí está la fuente HTML que Unity utiliza para su plantilla minima de WebGL.

<!DOCTYPE html>
<html lang="en-us">

    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Unity WebGL Player | %UNITY_WEB_NAME%</title>
    <script src="%UNITY_WEBGL_LOADER_URL%"></script>
    var unityInstance = UnityLoader.instantiate("unityContainer", "%UNITY_WEBGL_BUILD_URL%");
    <div id="unityContainer" style="width: %UNITY_WIDTH%px; height: %UNITY_HEIGHT%px; margin: auto"></div>

Both minimal and default templates can be found in the Unity installation folder under Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\WebGLTemplates on Windows or /PlaybackEngines/WebGLSupport/BuildTools/WebGLTemplates on Mac.

Adding a progress bar

Unity WebGL content will automatically render a default progress bar for you when it loads. You can override the default loading bar by providing your own progress function as an additional instantiation parameter. For example:

var unityInstance = UnityLoader.instantiate("unityContainer", "%UNITY_WEBGL_BUILD_URL%", {onProgress: UnityProgress});

where UnityProgress is a function of 2 arguments: unityInstance (identifies the unity instance the progressbar belongs to) and progress (a value from 0.0 to 1.0, providing information about the current loading progress).

Por ejemplo, la función de progreso en la plantilla WebGL predeterminada se ve de la siguiente manera:

var unityInstance = UnityLoader.instantiate("unityContainer", "%UNITY_WEBGL_BUILD_URL%", {onProgress: UnityProgress});

Por ejemplo, la función de progreso en la plantilla WebGL predeterminada se ve de la siguiente manera:

function UnityProgress(unityInstance, progress) {
  if (!unityInstance.Module)
  if (!unityInstance.logo) {
    unityInstance.logo = document.createElement("div");
    unityInstance.logo.className = "logo " + unityInstance.Module.splashScreenStyle;
  if (!unityInstance.progress) {    
    unityInstance.progress = document.createElement("div");
    unityInstance.progress.className = "progress " + unityInstance.Module.splashScreenStyle;
    unityInstance.progress.empty = document.createElement("div");
    unityInstance.progress.empty.className = "empty";
    unityInstance.progress.full = document.createElement("div");
    unityInstance.progress.full.className = "full";
  } = (100 * progress) + "%"; = (100 * (1 - progress)) + "%";
  if (progress == 1) = = "none";

You can use it as is or as reference for your own templates. Since the progress bar is completely implemented in JavaScript, you can customize or replace it to show anything you want as a progress indication.

  • 2018–10–18 Page amended

  • Updated in 5.6

  • WebGL instance renamed from gameInstance to unityInstance in 2019.1 NewIn20191

WebGL: Interacting with browser scripting
Bloqueo del cursor y modo de pantalla completa en WebGL
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。