版本:Unity 6 (6000.0)
语言English
  • C#

缓存

UnityEngine 中的类

/

实现于:UnityEngine.CoreModule

建议更改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法接受所有提交,但我们确实阅读了用户提出的每个建议更改,并在适用的情况下进行更新。

关闭

提交失败

由于某些原因,您的建议更改无法提交。请<a>稍后再试</a>。感谢您抽出时间帮助我们提高 Unity 文档的质量。

关闭

取消

描述

Caching 类允许您管理缓存的 AssetBundle,这些 AssetBundle 使用 UnityWebRequestAssetBundle.GetAssetBundle 下载。

注意:由于 AssetBundle 存储在 WebGL 平台的浏览器缓存中,因此 WebGL 中不支持 Cache API。

其他资源:DownloadHandlerAssetBundle

using System.Collections;
using UnityEngine;
using System.IO;
using System;
using UnityEngine.Networking;
using System.Collections.Generic;

public class Example : MonoBehaviour { IEnumerator DownloadAndCacheAssetBundle(string uri, string manifestBundlePath) { //Load the manifest AssetBundle manifestBundle = AssetBundle.LoadFromFile(manifestBundlePath); AssetBundleManifest manifest = manifestBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");

//Create new cache string today = DateTime.Today.ToLongDateString(); Directory.CreateDirectory(today); Cache newCache = Caching.AddCache(today);

//Set current cache for writing to the new cache if the cache is valid if (newCache.valid) Caching.currentCacheForWriting = newCache;

//Download the bundle Hash128 hash = manifest.GetAssetBundleHash("bundleName"); UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(uri, hash, 0); yield return request.SendWebRequest(); AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);

//Get all the cached versions List<Hash128> listOfCachedVersions = new List<Hash128>(); Caching.GetCachedVersions(bundle.name, listOfCachedVersions);

if (!AssetBundleContainsAssetIWantToLoad(bundle)) //Or any conditions you want to check on your new asset bundle { //If our criteria wasn't met, we can remove the new cache and revert back to the most recent one Caching.currentCacheForWriting = Caching.GetCacheAt(Caching.cacheCount); Caching.RemoveCache(newCache);

for (int i = listOfCachedVersions.Count - 1; i > 0; i--) { //Load a different bundle from a different cache request = UnityWebRequestAssetBundle.GetAssetBundle(uri, listOfCachedVersions[i], 0); yield return request.SendWebRequest(); bundle = DownloadHandlerAssetBundle.GetContent(request);

//Check and see if the newly loaded bundle from the cache meets your criteria if (AssetBundleContainsAssetIWantToLoad(bundle)) break; } } else { //This is if we only want to keep 5 local caches at any time if (Caching.cacheCount > 5) Caching.RemoveCache(Caching.GetCacheAt(1)); //Removes the oldest user created cache }

manifestBundle.Unload(true); bundle.Unload(true);

}

bool AssetBundleContainsAssetIWantToLoad(AssetBundle bundle) { return (bundle.LoadAsset<GameObject>("MyAsset") != null); //this could be any conditional } }

要存储最多五个相同 bundle 的缓存版本,并在您最新的缓存失效或下载的 Asset Bundle 出现问题时使用以前的缓存,请使用以下设置。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.IO;

public class Example2 : MonoBehaviour { public static class CacheWithPriority { public enum ResolutionType { High, Medium, Low, } static readonly Dictionary<ResolutionType, Cache> ResolutionCaches = new Dictionary<ResolutionType, Cache>();

public static void InitResolutionCaches() { string highResPath = "HighRes"; string medResPath = "MedRes"; string lowResPath = Application.streamingAssetsPath;

//Create cache paths Directory.CreateDirectory(highResPath); Directory.CreateDirectory(medResPath);

//Create the caches and add them to a Dictionary ResolutionCaches.Add(ResolutionType.High, Caching.AddCache(highResPath)); ResolutionCaches.Add(ResolutionType.Medium, Caching.AddCache(medResPath)); ResolutionCaches.Add(ResolutionType.Low, Caching.AddCache(lowResPath)); }

public static void PrioritizeCacheForLoading(ResolutionType resolutionToPrioritize) { //Move cache to the start of the queue Caching.MoveCacheBefore(ResolutionCaches[resolutionToPrioritize], Caching.GetCacheAt(0)); }

public static void SetResolutionCacheForWriting(ResolutionType resolutionToWriteTo) { Caching.currentCacheForWriting = ResolutionCaches[resolutionToWriteTo]; } }

AssetBundle currentTextureAssetBundle; IEnumerator RearrangeCacheOrderExample(string manifestBundlePath) { CacheWithPriority.InitResolutionCaches();

//Load the manifest AssetBundle manifestBundle = AssetBundle.LoadFromFile(manifestBundlePath); AssetBundleManifest manifest = manifestBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");

//We know we want to start loading from the Low Resolution Cache CacheWithPriority.PrioritizeCacheForLoading(CacheWithPriority.ResolutionType.Low);

//Load the low res bundle from StreamingAssets UnityWebRequest lowRequest = UnityWebRequestAssetBundle.GetAssetBundle("lowResBundlePath", manifest.GetAssetBundleHash("lowResBundle"), 0); yield return lowRequest; currentTextureAssetBundle = DownloadHandlerAssetBundle.GetContent(lowRequest);

//In the background we can start downloading our higher resolution bundles StartCoroutine(StartDownloadHigherResolutionBundles(manifest));

//Do work with low res bundle while the higher resolutions download...

//Unload the AssetBundle manifestBundle.Unload(true); }

IEnumerator StartDownloadHigherResolutionBundles(AssetBundleManifest manifest) { CacheWithPriority.SetResolutionCacheForWriting(CacheWithPriority.ResolutionType.Medium); UnityWebRequest medRequest = UnityWebRequestAssetBundle.GetAssetBundle("medResBundleUrl", manifest.GetAssetBundleHash("medResBundle"), 0); medRequest.SendWebRequest();

while (!medRequest.isDone) yield return null; SwitchTextureBundleTo(CacheWithPriority.ResolutionType.Medium, medRequest);

//Now you'll be using the medium resolution bundle

CacheWithPriority.SetResolutionCacheForWriting(CacheWithPriority.ResolutionType.High); UnityWebRequest highRequest = UnityWebRequestAssetBundle.GetAssetBundle("highResBundleUrl", manifest.GetAssetBundleHash("highResBundle"), 0); highRequest.SendWebRequest();

while (!highRequest.isDone) yield return null; SwitchTextureBundleTo(CacheWithPriority.ResolutionType.High, highRequest);

//Do work with the high resolution bundle now... }

void SwitchTextureBundleTo(CacheWithPriority.ResolutionType typeToSwitchTo, UnityWebRequest request) { //For performance, we tell the Caching system what cache we want it to search first CacheWithPriority.PrioritizeCacheForLoading(typeToSwitchTo); //Unload our current texture bundle currentTextureAssetBundle.Unload(true); //Load the new one from the passed in UnityWebRequest currentTextureAssetBundle = DownloadHandlerAssetBundle.GetContent(request); currentTextureAssetBundle.Unload(true); } }

能够拥有多个缓存允许您保留特定 Asset Bundle 的多个缓存版本。您可以将它们用于备份和回退等用途。

此示例演示了在启动后下载中分辨率和高分辨率纹理,并将其缓存在各自的相应缓存中。

静态属性

cacheCount返回缓存列表中的缓存计数。
compressionEnabled控制缓存数据的压缩。默认情况下启用。
currentCacheForWriting获取或设置应缓存 AssetBundle 的当前缓存。
defaultCache返回 Unity 内部添加的默认缓存。
ready如果缓存系统已准备好使用,则返回 true。

静态方法

AddCache使用给定路径添加缓存。
ClearAllCachedVersions从缓存中删除给定 AssetBundle 的所有缓存版本。
ClearCache删除当前应用程序缓存的所有 AssetBundle 内容。
ClearCachedVersion删除 AssetBundle 的给定版本。
ClearOtherCachedVersions从缓存中删除 AssetBundle 的所有缓存版本,除了指定的版本。
GetAllCachePaths返回缓存列表中所有缓存的路径。
GetCacheAt返回缓存列表中给定位置处的缓存。
GetCacheByPath返回具有给定缓存路径的缓存。
GetCachedVersions返回给定 AssetBundle 的所有缓存版本。
IsVersionCached检查 AssetBundle 是否已缓存。
MarkAsUsed将缓存文件的日期戳提升为当前时间。
MoveCacheAfter在缓存列表中将源缓存移动到目标缓存之后。
MoveCacheBefore在缓存列表中将源缓存移动到目标缓存之前。
RemoveCache从缓存列表中删除缓存。