Version: 2020.3
WebGL Player 设置
WebGL: Compressed builds and server configuration

构建和运行 WebGL 项目

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 in order 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 only generates this file for multi-threaded WebAssembly builds.
[ExampleBuild].data Asset data and Scenes.
[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 provided in the Player Settings (File > Build Settings > Player Settings > Splash Image). See the Splash Screen page for further information.

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.

The best way to view the WebGL Player locally is to use Unity’s Build And Run option (menu: File > Build And Run). 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 on setting up response headers, see WebGL: Compressed builds and server configuration.

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.

Build Settings

要访问 WebGL 构建设置,请打开 Build Settings 窗口 (File > Build Settings)。然后,从 Platform 列表中选择 WebGL

Build Settings Window
Build Settings Window

Development Build

选择 Development Build 设置时,Unity 会生成一个支持性能分析器的开发版和一个可供您查看应用程序中任何错误的开发控制台。此外,开发版不会缩减内容。开发版中的 JavaScript 是人类可读格式,而且 Unity 将保留函数名称,以便您可以查看错误的堆栈跟踪。但是,这意味着开发版将非常大,导致无法分发。 仅当启用了 Development Build 设置时,才能选择 Autoconnect ProfilerDeep Profiling Support

Autoconnect Profiler

启用 Autoconnect Profiler 设置可分析 Unity WebGL 内容的性能。对于 WebGL,无法像在其他平台上那样将性能分析器连接到正在运行的构建,因此必须使用此选项将内容连接到 Editor。这是因为性能分析器连接是使用 WebGL 上的 WebSockets 处理的,但 Web 浏览器仅允许来自内容的传出连接。

Deep Profiling Support

启用 Deep Profiling Support 设置可使 Unity Profiler 对应用程序中的每次函数调用都进行性能分析。如需了解更多信息,请参阅有关深度性能分析的文档。

播放器设置 (Player settings)

WebGL 在 Player 设置(菜单:__Edit__ > Project Settings__,然后选择 Player__ 类别)中有一些其他选项。

Other Settings

Strip Engine Code

打开 Other Settings 访问 Strip Engine Code 选项。默认情况下会选中此选项以启用 WebGL 的代码剥离。选中此选项后,Unity 不会包含未使用的任何类的代码。例如,如果不使用任何物理组件或函数,则会从构建中删除整个物理引擎。有关更多详细信息,请参阅下面的“剥离”部分。

Publishing Settings

Enable Exceptions

打开 Publishing Settings 访问 Enable ExceptionsEnable Exceptions 允许指定在运行时如何处理意外的代码行为(通常视为错误)。该设置具有以下选项:

  • __None__:如果不需要任何异常支持,请选择此选项。此选项可提供最佳性能和最小构建。使用此选项,抛出的任何异常都会导致内容因该设置中的错误而停止。
  • __Explicitly Thrown Exceptions Only__(默认设置):选择此选项可捕获从脚本中的 throw 语句显式指定的异常,并可确保调用 finally 代码块。请注意,选择此选项会使脚本中生成的 JavaScript 代码变得更长且更慢;仅当脚本是项目的主要瓶颈时,这才会成为问题。
  • __Full Without Stacktrace__:选择此选项可捕获:
    • 从脚本中的 throw 语句显式指定的异常(与 Explicitly Thrown Exceptions Only 选项一样)
    • Null 引用
    • 越界数组访问
  • __Full With Stacktrace__:此选项与上面的选项类似,但也捕获堆栈跟踪。Unity 通过在代码中嵌入对异常检查来生成这些异常,因此该选项会降低性能并增加浏览器内存使用量。仅用于调试,并始终在 64 位浏览器中进行测试。

Select Publishing Settings to access Data Caching.

Data Caching

To access Data Caching, select Publishing Settings (File > Build Settings > Player Settings > WebGL > Publishing Settings). 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.

以 WebGL 为目标进行发布时,必须保持较低的构建大小,让用户在内容启动之前等待合理的下载时间,这一点很重要。有关减小资源大小的一般提示,请参阅减小构建文件大小相关文档。

分发大小

以 WebGL 为目标进行发布时,必须保持较低的构建大小,让用户在内容启动之前等待合理的下载时间,这一点很重要。有关减小资源大小的一般提示,请参阅减小构建文件大小相关文档。

WebGL 特有的提示和技巧

  • 纹理导入器 (Texture Importer) 中为所有压缩纹理指定 Crunch 纹理压缩格式。

  • 不要部署开发版本;它们不会经过压缩或缩小,因此文件大小要大得多。

  • 打开 Player 设置(菜单:__Edit__ > Project Settings__,然后选择 Player__ 类别),打开 Publishing Settings 面板,并将 Enable Exceptions 设置为 __None__(如果在构建中不需要异常)。

  • 打开 Player 设置(菜单:__Edit__ > Project Settings__,然后选择 Player__ 类别),打开 Other Settings 面板,然后启用 Strip Engine Code 以确保进行高效构建。

  • 使用第三方托管的 dll 时要小心,因为它们可能包含大量依赖项,所以会显著增加生成的代码大小。

如果要构建发布版本,Unity 将根据在 WebGL Player 设置的 Publishing Settings 面板中选择的 Compression Format 来压缩构建输出文件。

有关这些选项的更多信息以及如何使用它们发布构建,请参阅有关部署压缩构建的文档。

AssetBundle

由于所有资源数据都需要在内容启动之前预先下载,因此应考虑将资源从主数据文件中移出到 AssetBundle中。这样,就能为内容创建一个小型加载场景,确保快速加载。然后,当用户继续浏览内容时,将按需动态加载资源。AssetBundle 还有助于进行资源数据内存管理:可通过调用 AssetBundle.Unload 从内存中卸载掉不再需要的资源的资源数据。

在 WebGL 平台上使用 AssetBundle 时的注意事项:

  • 在 AssetBundle 中使用未在主构建中使用的类类型时,Unity 可能会从构建中剥离这些类的代码。尝试从 AssetBundle 加载资源时,这可能会导致失败。请使用 BuildPlayerOptions.assetBundleManifestPath 修复该问题,或参阅下面有关剥离的部分以了解其他选项。

  • WebGL 不支持线程,但 http 下载内容仅在下载完成后才可用。因此,在下载完成时,Unity WebGL 构建需要在主线程上解压缩 AssetBundle 数据,而这会阻止主线程。为避免这种中断,LZMA AssetBundle 压缩不可用于 WebGL 上的 AssetBundle。此情况下使用 LZ4 对 AssetBundle 进行压缩,这种压缩格式可非常高效地按需进行解压缩。如果所需的压缩大小比 LZ4 能够提供的压缩大小更小,可将 Web 服务器配置为对 AssetBundle 使用 gzip 或 Brotli 压缩(基于 LZ4 压缩)。请参阅有关部署压缩构建的文档以详细了解如何执行此操作。

  • WebGL 支持通过 WWW.LoadFromCacheOrDownload 对 AssetBundle 进行缓存,可使用来自浏览器的 IndexedDB API 在用户的计算机上实现缓存。请注意,IndexedDB 可能对某些浏览器提供的支持有限,并且浏览器可能会请求用户授权将数据存储在磁盘上。请参阅有关 WebGL 浏览器兼容性的文档以了解更多信息。

剥离

默认情况下,Unity 会从构建中删除所有未使用的代码。可通过 Player 设置(菜单:__Edit__ > Project Settings__,然后选择 Player__ 类别)来更改此设置:选择 Other Settings 面板访问 Strip Engine Code 选项。最好在启用剥离的情况下进行构建。

启用代码剥离后,Unity 扫描会项目以查找是否使用了 UnityObject 派生的任何类(通过在脚本代码中或在场景中的序列化数据中引用)。然后从构建中删除所有未使用这些类的 Unity 子系统。这样可减少构建代码,从而减小下载和要解析的代码(因此代码运行速度更快,且占用的内存更少)。

代码剥离的问题

如果代码剥离时剥离了实际需要的代码,可能会导致项目出现问题。例如,如果在运行时加载的 AssetBundle 所包含的类未包括在主构建中,因此从项目中删除了这些 AssetBundle,这种情况下就可能出问题。发生这种情况时,浏览器的 JavaScript 控制台中会显示错误消息(随后可能会显示更多错误)。例如:

Could not produce class with ID XXX

To troubleshoot these errors, look up the ID (such as XXX in the example above) in the Class ID Reference to see which class it is trying to create an instance of. In such cases, you can force Unity to include the code for that class in the build, either by adding a reference to that class to your scripts or to your Scenes, or by adding a link.xml file to your project.

Below is an example which makes sure that the Collider class (and therefore the Physics module) gets preserved in a project. Add this XML code to a file called link.xml, and put that file into your Assets folder.

<linker>
    <assembly fullname="UnityEngine">
        <type fullname="UnityEngine.Collider" preserve="all"/>
    </assembly>
</linker>

如果怀疑剥离导致构建出现问题,还可尝试在测试期间禁用 Strip Engine Code 选项。

Unity does not provide a convenient way to see which modules and classes are included in a build, which would allow you to optimize your project to strip well. However, to get an overview of included classes and modules, you can look at the generated file Temp/StagingArea/Data/il2cppOutput/UnityClassRegistration.cpp after making a build.

Note that the Strip Engine Code option only affects Unity engine code. IL2CPP always strips byte code from your managed dlls and scripts. This can cause problems when you need to reference managed types dynamically through reflection rather than through static references in your code. If you need to access types through reflection, you may also need to set up a link.xml file to preserve those types. See the documentation page on iOS Build size optimization for more information on link.xml files.

移动构建输出文件

To change the location of your Build folder, modify the buildUrl variable in the WebGL Template index.html file.

To change the location of the files inside the Build folder, change their URLs (that is, dataUrl, wasmCodeUrl, wasmMemoryUrl, and wasmFrameworkUrl) in the parameters to the config variable in the index.html file.

You can specify URLs on external servers for these if you want to host your files on a content distribution network (CDN), but you need to make sure that the hosting server has enabled Cross Origin Resource Sharing (CORS) for this to work. See the manual page on WebGL networking for more information about CORS.

增量构建

The C++ code generated for your project by IL2CPP is compiled incrementally; that is, only generated C++ code that has changed since the last build is compiled again. Unchanged source code re-uses the same object files generated for the previous build. The object files used for incremental C++ builds are stored in the Library/il2cpp_cache directory in your Unity project.

To perform a clean, from-scratch build of the generated C++ code which doesn’t use incremental compiling, delete the Library/il2cpp_cache directory in your Unity project. Note that if the Unity Editor version differs from the one used for the previous WebGL build, Unity does a clean, from-scratch build automatically.


  • 在 Unity 2017.3 中添加了 Full Without Stacktrace
  • 在 Unity 2019.1 中删除了 asm.js 链接器目标
  • Build file updates and Data Caching added in Unity 2020.1
WebGL Player 设置
WebGL: Compressed builds and server configuration