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

Utilizando plantillas WebGL

Cuando construye un proyecto WebGL, Unity incrusta el player en una página HTML para que pueda reproducirse en el navegador. La página predeterminada es una página blanca simple con una barra de carga en un canvas gris. Alternativamente, puede seleccionar una plantilla mínima (con solo el código repetitivo necesario para ejecutar el contenido WebGL) en los Player Setting (menú: Edit > Project Settings > Player ).

Las páginas HTML integradas están bien para probar y demostrar un player mínimo, pero para propositos de producción, a menudo es deseable ver al player alojado en la página donde finalmente será desplegado. Por ejemplo, si el contenido de Unity interactúa con otros elementos en la página a través de la interfaz de llamadas externa, entonces debe probarse con una página que proporcione esos elementos interactivos. Unity le permite suministrar sus propias páginas para alojar el player usando 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.

Una vez creada la plantilla aparecerá con las opciones en el inspector de Player Settings (el nombre de la plantilla será el mismo que su carpeta). Opcionalmente, la carpeta puede tener un archivo llamado “thumbnail.png” con unas dimensiones de 128x128 pixeles. La imágen thumbnail será mostrada en el inspector para dar una idea de cómo se verá la página terminada.

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 para instanciar el juego: <script> var gameInstance = UnityLoader.instantiate("gameContainer", "%UNITY_WEBGL_BUILD_URL%");</script>

  • Una etiqueta <div> , que el id es utilizado en la función de instanciación. El contenido de este div será remplazado con la instancia deljuego.

UnityLoader.instantiate(container, url, override)

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

  • __container __ puede ser un elemento DOM (normalmente un elemento <div>) o un id de un elemento DOM. Si se proporciona el elemento DOM, el juego se creará de inmediato. Si se proporciona una id de un elemento DOM, se creará una instancia del juego una vez que se haya analizado todo el documento (lo que significa que puede proporcionar una identificación de un elemento DOM que aún no se haya creado en el momento de la llamada * UnityLoader.instantiate () * ).

  • 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 game instance. For example, you can override the compatibilityCheck, onProgress and popup functions, as those are properties of the game instance. Note that Module is a property of the game 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 (gameInstance, onsuccess, onerror) {
    if (!UnityLoader.SystemInfo.hasWebGL) {
      gameInstance.popup("Your browser does not support WebGL",
        [{text: "OK", callback: onerror}]);
    } else if (UnityLoader.SystemInfo.mobile) {
      gameInstance.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) {
      gameInstance.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 {
      onsuccess();
    }
  },
  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:-

<title>%UNITY_WEB_NAME%</title>

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

<title>MyPlayer</title>

… en la página anfitriona generada por la construcción. El conjunto completo de etiquetas se da abajo:-

  • 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 will 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.

Ejemplo

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">

  <head>
    <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>
    <script>
    var gameInstance = UnityLoader.instantiate("gameContainer", "%UNITY_WEBGL_BUILD_URL%");
    </script>
  </head>
  
  <body>
    <div id="gameContainer" style="width: %UNITY_WIDTH%px; height: %UNITY_HEIGHT%px; margin: auto"></div>
  </body>
  
</html>

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 gameInstance = UnityLoader.instantiate("gameContainer", "%UNITY_WEBGL_BUILD_URL%", {onProgress: UnityProgress});

where UnityProgress is a function of 2 arguments: gameInstance (identifies the game 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 gameInstance = UnityLoader.instantiate("gameContainer", "%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(gameInstance, progress) {
  if (!gameInstance.Module)
    return;
  if (!gameInstance.logo) {
    gameInstance.logo = document.createElement("div");
    gameInstance.logo.className = "logo " + gameInstance.Module.splashScreenStyle;
    gameInstance.container.appendChild(gameInstance.logo);
  }
  if (!gameInstance.progress) {   
    gameInstance.progress = document.createElement("div");
    gameInstance.progress.className = "progress " + gameInstance.Module.splashScreenStyle;
    gameInstance.progress.empty = document.createElement("div");
    gameInstance.progress.empty.className = "empty";
    gameInstance.progress.appendChild(gameInstance.progress.empty);
    gameInstance.progress.full = document.createElement("div");
    gameInstance.progress.full.className = "full";
    gameInstance.progress.appendChild(gameInstance.progress.full);
    gameInstance.container.appendChild(gameInstance.progress);
  }
  gameInstance.progress.full.style.width = (100 * progress) + "%";
  gameInstance.progress.empty.style.width = (100 * (1 - progress)) + "%";
  if (progress == 1)
    gameInstance.logo.style.display = gameInstance.progress.style.display = "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.


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