Version: Unity 6.0 (6000.0)
语言 : 中文
Unity Web 中的内存
Web 图形

Web 中的缓存行为

在 Unity Web 平台中,缓存 API 允许您将缓存在 .data 文件和 AssetBundle 中的资产数据存储在浏览器缓存中。浏览器缓存的存储限制(例如最大文件大小、最大整体缓存大小和驱逐条件)取决于您使用的浏览器和平台。有关更多信息,请参阅浏览器存储限制和驱逐条件

数据缓存

要访问数据缓存,请从文件 (File) > 构建设置 (Build Settings) > 播放器设置 (Player Settings) 中打开 Web 的发布设置 (Publishing Settings)。这样,浏览器会将主数据文件缓存到 IndexedDB 数据库中。

使用默认浏览器 HTTP 缓存并不能保证浏览器缓存特定响应。这是因为浏览器 HTTP 缓存空间有限,浏览器可能无法缓存过大的文件。

为了提高加载速度,IndexedDB 允许您缓存超过浏览器限制的文件。当你缓存更多的文件时,就增加了在下一次运行该构建版本时,已下载的内容在用户机器上可用的几率。

数据缓存仅为 HTTP 响应缓存 IndexedDB 缓存中的 .data 文件。要缓存 AssetBundle,需要启用数据缓存并覆盖 unityInstance.Module.cacheControl()。为此,请确保 Module.cacheControl(url) 返回所请求的 AssetBundle URL 的 must-revalidate。例如,可以在 createUnityInstance() 返回的 Promise 的实现回调中覆盖 unityInstance.Module.cacheControl() 函数。有关 createUnityInstance() 的更多信息,请参阅压缩构建和服务器配置

自定义 Web 缓存行为

默认情况下,Web 缓存会存储资产数据文件 .data 和 AssetBundle 文件 .bundle,并在从缓存加载它们之前重新验证它们。您可以通过添加新的 Web 模板来更改 UnityLoader 配置来更改此行为。

以下示例显示了向 index.html 文件中的 UnityLoader 配置添加自定义 cacheControl 函数的情况。

var config = {
   // ...
#if USE_DATA_CACHING
   cacheControl: function (url) {
     // Caching enabled for .data and .bundle files.
     // Revalidate if file is up to date before loading from cache
     if (url.match(/\.data/) || url.match(/\.bundle/)) {
         return "must-revalidate";
     }

     // Caching enabled for .mp4 and .custom files
     // Load file from cache without revalidation.
     if (url.match(/\.mp4/) || url.match(/\.custom/)) {
         return "immutable";
     }

     // Disable explicit caching for all other files.
     // Note: the default browser cache may cache them anyway.
     return "no-store";
   },
#endif
   // ...
}

cacheControl 函数将请求的 URL 作为参数并返回以下之一:

  • must-revalidate - 如果函数返回 must-revalidate,则缓存会返回到启用状态,并在从缓存加载文件之前重新验证文件。

  • immutable - 如果函数返回 immutable,则启用缓存并从缓存加载文件,无需重新验证。

  • no-store - 如果该函数返回 no-store,则禁用缓存。

浏览器会自动存储(缓存)某些文件类型,例如 .html、.js、.css、.json、.jpg、.png,因此它们不需要显式存储在 Web 缓存中。Web 缓存的典型候选对象包括大型文件和使用自定义文件格式的文件。

Unity Web 中的内存
Web 图形