To create a build for WebGL, go to File > Build Settings from Unity’s main menu. In the Platform list, select WebGL and then click Switch Platform.
When you have configured the Build Settings, choose one the following options:
The Unity build system for WebGLA JavaScript API that renders 2D and 3D graphics in a web browser. The Unity WebGL build option allows Unity to publish content as JavaScript programs which use HTML5 technologies and the WebGL rendering API to run Unity content in a web browser. More info
See in Glossary supports the following settings:
Setting | Function | |
---|---|---|
Texture CompressionA method of storing data that reduces the amount of storage space it requires. See Texture Compression, Animation Compression, Audio Compression, Build Compression. See in Glossary |
The texture compression3D Graphics hardware requires Textures to be compressed in specialized formats which are optimized for fast Texture sampling. More info See in Glossary format to use for the build. The options are: |
|
Use Player Settings | This is the default selection. It uses the texture compression format you set in the Player settingsSettings that let you set various player-specific options for the final game built by Unity. More info See in Glossary window. |
|
ETC2 | Uses ETC2 format, which is widely supported on mobile devices. | |
ASTC | Uses ASTC format, which is widely supported on mobile devices. | |
DXT | Uses DXT format, which is widely supported on desktop devices. | |
Development BuildA development build includes debug symbols and enables the Profiler. More info See in Glossary |
Enable this setting to include scripting debug symbols and the Profiler in your build. When you enable this, Unity sets the DEVELOPMENT_BUILD scripting define. You should use this setting only when you want to test your application. The development builds don’t minify content, which means the development builds are large to distribute. |
|
Code Optimization | Select the optimization mode to use for compiling the WebGL code. | |
Speed | This is the default setting. Select this to generate WebGL code that’s optimized for runtime performance. | |
Size | Select this to generate WebGL code that’s optimized for build size. This is useful for reducing WebGL games to the smallest downloadable size, and for large projects if a mobile browser (Android or iOS) refuses to load the default optimize-for-speed WebAssembly builds as too large for mobile devices to consume. | |
Autoconnect Profiler | Typically, when enabled, this setting allows you to automatically connect the Unity Profiler to your build. However for WebGL, as you can’t connect the ProfilerA window that helps you to optimize your game. It shows how much time is spent in the various areas of your game. For example, it can report the percentage of time spent rendering, animating, or in your game logic. More info See in Glossary to a running build, use this option to connect the content to the Editor instead. This is because the Profiler connection is handled using WebSockets on WebGL, but a web browser only allows outgoing connections from the content. For this setting to be available, you should enable the Development Build option. |
|
Deep Profiling | Enable this setting to activate Deep Profiling in the Profiler. This makes the Profiler instrument every function call in your application and returns more detailed profiling data. When you enable Deep Profiling Support, it might slow down script execution. This option is only available if you enable the Development Build option. | |
Build | Use it to build your application. | |
Build And Run | Use it to view the WebGL Player locally. Unity uses a local web server to host your build, and opens it from a localhost URL. Alternatively, you can use a custom local web server with properly configured response headers. For more information, see Compressed builds and server configuration. |
For changing the settings for Asset Import Overrides, see Build Settings.
The Build
folder contains the following files ([ExampleBuild]
represents the name of the target build folder).
File name | Contains |
---|---|
[ExampleBuild].loader.js |
The JavaScript code that the web page needs to load the Unity content. |
[ExampleBuild].framework.js |
JavaScript runtime and plugins. |
[ExampleBuild].wasm |
WebAssembly binary. |
[ExampleBuild].mem |
A binary image to initialize the heap memory for your Player. Unity generates this file for multi-threaded WebAssembly builds only. |
[ExampleBuild].data |
Asset data and ScenesA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info See in Glossary. |
[ExampleBuild].symbols.json |
Debug symbol names necessary to demangle an error stack trace. This file is only generated for Release builds when you enable the Debug Symbols option (File > Build Settings > Player Settings.) |
[ExampleBuild].jpg |
A background image, which displays while the build is loading. This file is only generated when a Background Image is available in the Player Settings (File > Build Settings > Player Settings > Splash Image). For more information, see Splash Screen. |
If you enable a Compression Method for your build, Unity identifies the extension that corresponds with the compression method and adds this extension to the names of the files inside the Build subfolder. If you enable Decompression Fallback, Unity appends the extension .unityweb
to the build file names. Otherwise, Unity appends the extension .gz
for the Gzip compression method, or .br
for the Brotli compression method.
For more information, see WebGL: Compressed builds and server configuration.
If you enable Name Files As Hashes in the Player Settings, Unity uses the hash of the file content instead of the default filename. This applies to each file in the build folder. This option allows you to upload updated versions of the game builds into the same folder on the server, and only upload the files which have changed between build iterations.
Note: Opening a Player directly from the file system might not work in some browsers. This is due to security restrictions applied to local file URLs.
Enable the Deep Profiling Support setting to make the Unity Profiler profile every function call in your application. For more information see the documentation on Deep Profiling.
Open Publishing Settings to access Enable Exceptions. Enable Exceptions allows you to specify how unexpected code behavior (also known as errors) is handled at run time. It has these options:
throw
statement in your scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More infofinally
blocks are called. Note that selecting this option makes the generated JavaScript code from your scripts longer and slower; This might only be an issue if scripts are the main bottleneck in your project.throw
statements in your scripts (the same as in the Explicitly Thrown Exceptions Only option)
To access Data Caching, go to Publishing Setings via File > Build Settings > Player Settings > WebGL. This enables the browser to cache the main data files into the IndexedDB database.
Using the default browser HTTP cache does not guarantee that the browser caches a particular response. This is because the browser HTTP cache has limited space, and the browser might not be able to cache files that are too large.
To improve your loading speed, IndexedDB allows you to cache files above the browser limit. When you cache more files, you increase the chance that downloaded content is available on the user’s machine during the next run of the build.
Data Caching only caches the .data
files in the IndexedDB cache for HTTP responses. To cache AssetBundles, you need to enable Data Caching and override unityInstance.Module.cacheControl()
.
To do this, make sure Module.cacheControl(url)
returns must-revalidate
for the requested AssetBundle URL. For example, you can override the unityInstance.Module.cacheControl() function in the fulfillment callback of the Promise that createUnityInstance() returns.
For further information on createUnityInstance() see WebGL: Compressed builds and server configuration.
The texture compression setting in WebGL lets you create builds that target platforms based on the texture compression formats they support. The texture compression format value you set here has priority over the Player settings texture compression format value. To run your game on both desktop and mobile browsers with compressed textures, you might want to create two builds: * Targeting desktop browsers with DXT set as the texture compression format * Targeting mobile browsers with ASTC set as the texture compression format
You can run a build for both desktop browsers and mobile browsers with the corresponding texture compression formats simultaneously using a script. For example:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Diagnostics;
using System.IO;
using UnityEditor.Build.Reporting;
public class comboBuild
{
//This creates a menu item to trigger the dual builds https://docs.unity.cn/ScriptReference/MenuItem.html
[MenuItem("Game Build Menu/Dual Build")]
public static void BuildGame()
{
//This builds the player twice: a build with desktop-specific texture settings (WebGL_Build) as well as mobile-specific texture settings (WebGL_Mobile), and combines the necessary files into one directory (WebGL_Build)
string dualBuildPath = "WebGLBuilds";
string desktopBuildName = "WebGL_Build";
string mobileBuildName = "WebGL_Mobile";
string desktopPath = Path.Combine(dualBuildPath, desktopBuildName);
string mobilePath = Path.Combine(dualBuildPath, mobileBuildName);
string[] scenes = new string[] {"Assets/scene.unity"};
EditorUserBuildSettings.webGLBuildSubtarget = WebGLTextureSubtarget.DXT;
BuildPipeline.BuildPlayer(scenes, desktopPath, BuildTarget.WebGL, BuildOptions.Development);
EditorUserBuildSettings.webGLBuildSubtarget = WebGLTextureSubtarget.ASTC;
BuildPipeline.BuildPlayer(scenes, mobilePath, BuildTarget.WebGL, BuildOptions.Development);
// Copy the mobile.data file to the desktop build directory to consolidate them both
FileUtil.CopyFileOrDirectory(Path.Combine(mobilePath, "Build", mobileBuildName + ".data"), Path.Combine(desktopPath, "Build", mobileBuildName + ".data"));
}
}
You can modify the WebGL template’s index.html
file to select the appropriate data file if there’s support for the texture compression format extension:
// choose the data file based on whether there's support for the ASTC texture compression format
var dataFile = "/{{{ DATA_FILENAME }}}";
var c = document.createElement("canvas");
var gl = c.getContext("webgl");
var gl2 = c.getContext("webgl2");
if ((gl && gl.getExtension('WEBGL_compressed_texture_astc')) || (gl2 &&
gl2.getExtension('WEBGL_compressed_texutre_astc'))) {
dataFile = "/WebGL_Mobile.data";
}
var buildUrl = "Build";
var loaderUrl = buildUrl + "/{{{ LOADER_FILENAME }}}";
var config = {
dataUrl: buildUrl + dataFile,
frameworkUrl: buildUrl + "/{{{ FRAMEWORK_FILENAME }}}",
#if USE_WASM
codeUrl: buildUrl + "/{{{ CODE_FILENAME }}}",
#endif
#if MEMORY_FILENAME
memoryUrl: buildUrl + "/{{{ MEMORY_FILENAME }}}",
#endif
#if SYMBOLS_FILENAME
symbolsUrl: buildUrl + "/{{{ SYMBOLS_FILENAME }}}",
#endif
streamingAssetsUrl: "StreamingAssets",
companyName: {{{ JSON.stringify(COMPANY_NAME) }}},
productName: {{{ JSON.stringify(PRODUCT_NAME) }}},
productVersion: {{{ JSON.stringify(PRODUCT_VERSION) }}},
showBanner: unityShowBanner,
};