public static async Task <AssetBundle> GetAssetBundle(string url, CancellationTokenSource cancelationToken, System.Action <float> progress = null, bool caching = true) { UnityWebRequest request; CachedAssetBundle assetBundleVersion = await GetAssetBundleVersion(url); if (Caching.IsVersionCached(assetBundleVersion) || (caching && ResourceCache.CheckFreeSpace(await GetSize(url)))) { request = UnityWebRequestAssetBundle.GetAssetBundle(url, assetBundleVersion, 0); } else { request = UnityWebRequestAssetBundle.GetAssetBundle(url); } UnityWebRequest uwr = await SendWebRequest(request, cancelationToken, Caching.IsVersionCached(assetBundleVersion)?null : progress); if (uwr != null && !uwr.isHttpError && !uwr.isNetworkError) { AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(uwr); if (caching) { // Deleting old versions from the cache Caching.ClearOtherCachedVersions(assetBundle.name, assetBundleVersion.hash); } return(assetBundle); } else { throw new Exception(string.Format("Netowrk.GetAssetBundle - {0} {1}", uwr.error, uwr.url)); } }
/// <summary> /// CoreABDownloader is BOTH AssetBundle DOWNLOADER and USER /// It checks AB_Hash with Cache then download Latest AB if it has to /// </summary> /// <param name="_fileURL"></param> /// <param name="_success"></param> /// <param name="_fail"></param> /// <param name="_progress"></param> IEnumerator CoreABDownloader(ABFileURL _fileURL, Action <UnityWebRequest> _success = null, Action <string> _fail = null, Action <float> _progress = null) { if (myABM == null) { Debug.LogError("ABM not loaded!"); } Hash128 abHash = myABM.GetAssetBundleHash(_fileURL.fileName); //Clean up older AB in Cache Caching.ClearOtherCachedVersions(_fileURL.fileName, abHash); Debug.Log("Try to Download " + _fileURL); #if UNITY_2018_1_OR_NEWER using (var _uwr = UnityWebRequestAssetBundle.GetAssetBundle(_fileURL.fullURL, abHash, 0)) #else using (var _uwr = UnityWebRequest.GetAssetBundle(_fileURL.fullURL, abHash, 0)) #endif { _uwr.SendWebRequest(); yield return(null); while (!_uwr.isDone) { if (_progress != null) { _progress(_uwr.downloadProgress); } yield return(null); } if (_uwr.isNetworkError || _uwr.isHttpError) { Debug.LogError("File Download Failed " + _uwr.error); if (_fail != null) { _fail(_uwr.error); } } else { if (_success != null) { _success(_uwr); } } yield return(null); yield return(null); yield return(null); } }
/// <summary> /// 清除除了allBundleInfo中其他版本号的资源 /// </summary> /// <param name="allBundleInfo"></param> private void ClearOtherCachedVersions(AllBundleInfo allBundleInfo) { foreach (var singleBundleInfo in allBundleInfo.BundleInfoList) { bool success = Caching.ClearOtherCachedVersions(singleBundleInfo.Value.bundleName, Hash128.Parse(singleBundleInfo.Value.bundleHash128)); string bundleName = singleBundleInfo.Value.bundleName; Hash128 hash128 = Hash128.Parse(singleBundleInfo.Value.bundleHash128); Debug.Log(string.Format("缓存bundleName:{0},清理版本号hash128:{1}之外的资源,success:{2}", bundleName, hash128, success)); } }
public override void Complete() { if (!m_Aborted) { //clear other cached version string bundleName = Path.GetFileName(bundleUrl); Caching.ClearOtherCachedVersions(bundleName, Hash128.Parse(hash)); base.Complete(); } }
private void OnInitializationComplete(AssetBundle manifestBundle, string bundleName, uint version) { if (manifestBundle == null) { Debug.LogError("AssetBundleManifest not found."); var streamingAssetsDecorator = handler as StreamingAssetsBundleDownloadDecorator; if (streamingAssetsDecorator != null) { PrimaryManifest = PrimaryManifestType.StreamingAssets; Manifest = streamingAssetsDecorator.GetManifest(); if (Manifest != null) { Debug.LogWarning("Falling back to streaming assets for bundle information."); } } } else { Manifest = manifestBundle.LoadAsset <AssetBundleManifest>("assetbundlemanifest"); PlayerPrefs.SetInt(MANIFEST_PLAYERPREFS_KEY, (int)version); #if UNITY_2017_1_OR_NEWER Caching.ClearOtherCachedVersions(bundleName, new Hash128(0, 0, 0, version)); #endif } if (Manifest == null) { PrimaryManifest = PrimaryManifestType.None; } else { Initialized = true; if (useHash) { GenerateNameHashMaps(Manifest); } } var inProgress = downloadsInProgress[MANIFEST_DOWNLOAD_IN_PROGRESS_KEY]; downloadsInProgress.Remove(MANIFEST_DOWNLOAD_IN_PROGRESS_KEY); inProgress.OnComplete(manifestBundle); // Need to do this after OnComplete, otherwise the bundle will always be null if (manifestBundle != null) { manifestBundle.Unload(false); } }
/// <summary> /// オンラインプロセス開始イベント /// </summary> /// <returns>コルーチン</returns> protected override System.Collections.IEnumerator OnStartedOnlineProcess() { m_ErrorCode = AssetBundleErrorCode.Null; var fileNameAndURL = manager.GetAssetBundleFileNameAndURL(nameWithVariant); m_DownloadWork = new DownloadWork { url = fileNameAndURL.url, hash = manager.catalog.GetAssetBundleHash(nameWithVariant), crc = manager.catalog.GetAssetBundleCrc(nameWithVariant) }; #if UNITY_2018_1_OR_NEWER m_DownloadWork.request = UnityWebRequestAssetBundle.GetAssetBundle(m_DownloadWork.url, m_DownloadWork.hash, m_DownloadWork.crc); #else m_DownloadWork.request = UnityWebRequest.GetAssetBundle(m_DownloadWork.url, m_DownloadWork.hash, m_DownloadWork.crc); #endif var sendWebRequest = m_DownloadWork.request.SendWebRequest(); var progress = -1.0f; var startTime = Time.realtimeSinceStartup; while (!sendWebRequest.isDone) { yield return(null); if (progress != sendWebRequest.progress) { //進行 progress = sendWebRequest.progress; startTime = Time.realtimeSinceStartup; } else if (manager.downloadTimeoutSeconds < (Time.realtimeSinceStartup - startTime)) { //タイムアウト時間の停滞 break; } } if (m_DownloadWork.request.isNetworkError || m_DownloadWork.request.isHttpError) { AssetBundleErrorCodeUtility.TryParse(m_DownloadWork.request, out m_ErrorCode); } else { Caching.ClearOtherCachedVersions(fileNameAndURL.fileName, m_DownloadWork.hash); } yield return(base.OnStartedOnlineProcess()); }
// Where we actuall call WWW to download the assetBundle. static protected bool LoadAssetBundleInternal(string assetBundleName, bool isLoadingAssetBundleManifest) { // Already loaded. LoadedAssetBundle bundle = null; m_LoadedAssetBundles.TryGetValue(assetBundleName, out bundle); if (bundle != null) { bundle.m_ReferencedCount++; return(true); } // @TODO: Do we need to consider the referenced count of WWWs? // In the demo, we never have duplicate WWWs as we wait LoadAssetAsync()/LoadLevelAsync() to be finished before calling another LoadAssetAsync()/LoadLevelAsync(). // But in the real case, users can call LoadAssetAsync()/LoadLevelAsync() several times then wait them to be finished which might have duplicate WWWs. if (m_DownloadingWWWs.ContainsKey(assetBundleName)) { return(true); } WWW download = null; string url = m_BaseDownloadingURL + assetBundleName; //Debug.Log("download start >> "+url); // For manifest assetbundle, always download it as we don't have hash for it. if (isLoadingAssetBundleManifest) { download = new WWW(url); } else { download = WWW.LoadFromCacheOrDownload(url, m_AssetBundleManifest.GetAssetBundleHash(assetBundleName), 0); //Unity2017 バージョン違いを消す if (Caching.ClearOtherCachedVersions(assetBundleName, m_AssetBundleManifest.GetAssetBundleHash(assetBundleName)) == false) { Debug.LogWarning("ClearOtherCachedVersions"); } } m_DownloadingWWWs.Add(assetBundleName, download); return(false); }
public static int ClearOtherCachedVersions_s(IntPtr l) { int result; try { string assetBundleName; LuaObject.checkType(l, 1, out assetBundleName); Hash128 hash; LuaObject.checkValueType <Hash128>(l, 2, out hash); bool b = Caching.ClearOtherCachedVersions(assetBundleName, hash); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return(result); }
private IEnumerator _downloadRes() { string url; for (int i = 0; i < m_need_download_res.Count;) { url = string.Format("{0}/{1}", m_res_server_url, m_need_download_res[i].BundleName); if (Caching.IsVersionCached(new CachedAssetBundle(m_need_download_res[i].BundleName, Hash128.Parse(m_need_download_res[i].Md5)))) { m_need_download_res.RemoveAt(i); continue; } Debug.LogFormat("开始下载资源:{0}", url); using (UnityWebRequest www = UnityWebRequest.GetAssetBundle(url, new CachedAssetBundle(m_need_download_res[i].BundleName, Hash128.Parse(m_need_download_res[i].Md5)), 0)) { yield return(www.SendWebRequest()); if (www.isHttpError || www.isNetworkError) { Debug.LogErrorFormat("资源:{0}下载失败 {1}", url, www.error); ++i; continue; } Debug.LogFormat("资源:{0}下载完成", url); Caching.ClearOtherCachedVersions(m_need_download_res[i].BundleName, Hash128.Parse(m_need_download_res[i].Md5)); m_need_download_res.RemoveAt(i); } } if (m_need_download_res.Count == 0 && m_complete != null) { ResManager.Instance.SaveResList(m_server_res.bytes); ResManager.Instance.SetAllConfig(m_server_res_config); m_complete(); } else { StartCoroutine(_downloadRes()); } }
private IEnumerator LoadAssetBundleFromFile(Dictionary <string, GameResAssetBundle> bundleGroupMap, string bundleName, string manifestName, string hash, string fullPath, System.Action <bool> onLoadDone) { var realHash = Hash128.Parse(hash); var req = AssetBundle.LoadFromFileAsync(fullPath); while (!req.isDone) { yield return(null); } if (req.assetBundle == null) { onLoadDone(false); yield break; } if (bundleGroupMap.ContainsKey(bundleName) && bundleGroupMap[bundleName].hash != hash) { UnLoadAssetBundle(bundleName, manifestName); } if (!bundleGroupMap.ContainsKey(bundleName)) { bundleGroupMap.Add(bundleName, new GameResAssetBundle() { hash = hash, assetBundle = req.assetBundle, }); } // 清除缓存中除当前使用的 Caching.ClearOtherCachedVersions(bundleName, realHash); onLoadDone(true); FTDebug.LogWarning(string.Format("LoadAssetBundleFromFile Name[{0}] Path[{1}]", bundleName, fullPath)); }
public void LoadProjcetAssetBundles(string inProjectID) { // Debug.Log("PersistentDataPath: "+Application.persistentDataPath); // SetProjectPath(inProjectID); Loading loading = loadingManager.AddALoading(0); bool checkFile = false; if (checkFile = File.Exists(pathAndURL.localProjectAssetBundlesInfoPath)) { string jsonStr = File.ReadAllText(pathAndURL.localProjectAssetBundlesInfoPath); localProjectAssetBundlesInfo = JsonUtility.FromJson <ProjectAssetBundlesInfo>(jsonStr); netCtrlManager.WebRequest( "同步服务器", pathAndURL.serverProjectAssetBundlesInfoPath, loading.LoadingAnimation, (NetCtrlManager.RequestHandler r, UnityWebRequestAsyncOperation a, string info) => { Debug.Log("ServerProjectAssetBundlesInfo Load Failed!"); }, (DownloadHandler t) => { serverProjectAssetBundlesInfo = JsonUtility.FromJson <ProjectAssetBundlesInfo>(t.text); // if (globalDebug) GlobalDebug.ReplaceLine(t.text, 15); //判断两个资源的生成时间,如果时间不一样表示资源以过期,要删去旧的资源以便重新下载 if (serverProjectAssetBundlesInfo.buildTime != localProjectAssetBundlesInfo.buildTime) { File.WriteAllText(pathAndURL.localProjectAssetBundlesInfoPath, t.text); for (int i = 0; i < serverProjectAssetBundlesInfo.sceneAssetBundle.Length; i++) { Caching.ClearOtherCachedVersions(pathAndURL.projectPath + serverProjectAssetBundlesInfo.sceneAssetBundle[i], Hash128.Parse(serverProjectAssetBundlesInfo.sceneAssetBundleHash[i])); } } StartLoadAssetBundle(serverProjectAssetBundlesInfo); }, null, null ); } else { netCtrlManager.WebRequest( "同步服务器", pathAndURL.serverProjectAssetBundlesInfoPath, loading.LoadingAnimation, (NetCtrlManager.RequestHandler r, UnityWebRequestAsyncOperation a, string info) => { Debug.Log("ServerProjectAssetBundlesInfo Load Failed!"); }, (DownloadHandler t) => { // if (globalDebug) GlobalDebug.ReplaceLine(t.text, 15); serverProjectAssetBundlesInfo = JsonUtility.FromJson <ProjectAssetBundlesInfo>(t.text); File.WriteAllText(pathAndURL.localProjectAssetBundlesInfoPath, t.text); StartLoadAssetBundle(serverProjectAssetBundlesInfo); }, null, null ); } // if(globalDebug) GlobalDebug.ReplaceLine("HasLoaclInfo.txt:" + checkFile.ToString(), 16); }
void LoadBGM(Uri uri, string assetBundleName, Hash128 hash, uint crc, int bgmID) { Debug.Log(Caching.ready); //構造体生成 var cachedAssetBundle = new CachedAssetBundle(assetBundleName, hash); //指定バージョン以外削除 //新しいCRCの場合は古いほうを削除 Caching.ClearOtherCachedVersions(cachedAssetBundle.name, cachedAssetBundle.hash); if (Caching.IsVersionCached(cachedAssetBundle)) { Debug.Log("キャッシュから"); //キャッシュ存在 string dataPath = AssetBundlePath(cachedAssetBundle); Debug.Log(dataPath); var op = UnityEngine.AssetBundle.LoadFromFileAsync(dataPath); op.completed += (obj) => { Debug.Log("ダウンロード成功"); AssetBundle bundle = op.assetBundle; var prefab = bundle.LoadAllAssets <AudioClip>(); SoundManager.instance.SetAudioClip(bgmID, prefab[0]); GenerateBGM(bgmID + 1); ShowLoad(); }; } else { Debug.Log("サーバーから"); var request = UnityWebRequestAssetBundle.GetAssetBundle(uri, cachedAssetBundle, crc); var op = request.SendWebRequest(); op.completed += (obj) => { if (op.webRequest.isHttpError || op.webRequest.isNetworkError) { Debug.Log($"ダウンロードに失敗しました!! error:{op.webRequest.error}"); LoadFailed(); } else { Debug.Log("ダウンロード成功"); AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request); var prefab = bundle.LoadAllAssets <AudioClip>(); SoundManager.instance.SetAudioClip(bgmID, prefab[0]); GenerateBGM(bgmID + 1); ShowLoad(); } }; } }
void LoadCard(Uri uri, string assetBundleName, Hash128 hash, uint crc, int cardID, bool isDish) { Debug.Log(Caching.ready); //構造体生成 var cachedAssetBundle = new CachedAssetBundle(assetBundleName, hash); //指定バージョン以外削除 //新しいCRCの場合は古いほうを削除 Caching.ClearOtherCachedVersions(cachedAssetBundle.name, cachedAssetBundle.hash); Debug.Log("cardID " + cardID); if (Caching.IsVersionCached(cachedAssetBundle)) { Debug.Log("キャッシュから"); //キャッシュ存在 string dataPath = AssetBundlePath(cachedAssetBundle); Debug.Log(dataPath); var op = UnityEngine.AssetBundle.LoadFromFileAsync(dataPath); op.completed += (obj) => { Debug.Log("ダウンロード成功"); AssetBundle bundle = op.assetBundle; var prefab = bundle.LoadAllAssets <CardEntity>(); CardEntity cardEntity = new CardEntity(); cardEntity = prefab[0] as CardEntity; Sprite[] icon = bundle.LoadAllAssets <Sprite>(); if (icon[0] != null) { cardEntity.icon = icon[0]; } if (!isDish) { if (icon[1] != null) { cardEntity.glowIcon = icon[1]; } } if (isDish) { cardData.dishCardEntity[cardID] = cardEntity; } else { cardData.ingCardEntity[cardID] = cardEntity; } ShowLoad(); GenerateCard(cardID + 1, isDish); }; } else { Debug.Log("サーバーから"); var request = UnityWebRequestAssetBundle.GetAssetBundle(uri, cachedAssetBundle, crc); var op = request.SendWebRequest(); op.completed += (obj) => { if (op.webRequest.isHttpError || op.webRequest.isNetworkError) { Debug.Log($"ダウンロードに失敗しました!! error:{op.webRequest.error}"); LoadFailed(); } else { Debug.Log("ダウンロード成功"); AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request); var prefab = bundle.LoadAllAssets <CardEntity>(); CardEntity cardEntity = new CardEntity(); cardEntity = prefab[0] as CardEntity; Sprite[] icon = bundle.LoadAllAssets <Sprite>(); if (icon[0] != null) { cardEntity.icon = icon[0]; } if (!isDish) { if (icon[1] != null) { cardEntity.glowIcon = icon[1]; } } if (isDish) { cardData.dishCardEntity[cardID] = cardEntity; } else { cardData.ingCardEntity[cardID] = cardEntity; } ShowLoad(); GenerateCard(cardID + 1, isDish); } }; } }
private IEnumerator LoadAssetBundleFromCache(Dictionary <string, GameResAssetBundle> bundleGroupMap, string bundleName, string manifestName, string hash, string[] urls, System.Action <bool> onLoadDone) { var realHash = Hash128.Parse(hash); bool success = false; foreach (string url in urls) { float checkTimeOutTime = Time.time; float progress = 0; var webRequest = GameWebRequest.SendAssetBundleWebRequest(url, realHash, true); while (!webRequest.request.isDone) { if (!string.IsNullOrEmpty(webRequest.request.error)) { break; } if (progress != webRequest.request.downloadProgress) { checkTimeOutTime = Time.time; } else if (Time.time - checkTimeOutTime >= 5) { break; } yield return(null); } if (!string.IsNullOrEmpty(webRequest.request.error) || !webRequest.request.isDone) { FTDebug.LogWarning(string.Format("Failed To LoadAssetBundleFromCache Name[{0}] From[{1}] Error[{2}]", bundleName, url, webRequest.request.error)); GameWebRequest.DestroyAssetBundleWebRequest(webRequest); Caching.ClearCachedVersion(bundleName, realHash); continue; } AssetBundle assetBundle = null; try { assetBundle = DownloadHandlerAssetBundle.GetContent(webRequest.request); if (assetBundle == null) { FTDebug.LogWarning(string.Format("Failed To LoadAssetBundleFromCache Name[{0}] From[{1}] Error[AssetBundle is Null]", bundleName, url)); GameWebRequest.DestroyAssetBundleWebRequest(webRequest); Caching.ClearCachedVersion(bundleName, realHash); continue; } } catch (System.Exception e) { FTDebug.LogWarning(string.Format("Failed To LoadAssetBundleFromCache Name[{0}] From[{1}] Error[{2}]", bundleName, url, e.Message)); GameWebRequest.DestroyAssetBundleWebRequest(webRequest); Caching.ClearCachedVersion(bundleName, realHash); continue; } if (bundleGroupMap.ContainsKey(bundleName) && bundleGroupMap[bundleName].hash != hash) { UnLoadAssetBundle(bundleName, manifestName); } if (!bundleGroupMap.ContainsKey(bundleName)) { bundleGroupMap.Add(bundleName, new GameResAssetBundle() { hash = hash, assetBundle = assetBundle, }); } GameWebRequest.DestroyAssetBundleWebRequest(webRequest); success = true; FTDebug.Log(string.Format("LoadAssetBundleFromCache Name[{0}] From[{1}]", bundleName, url)); // 清除除当前使用的 Caching.ClearOtherCachedVersions(bundleName, realHash); break; } onLoadDone(success); }
//如果OnCached非空,只会缓存AssetBundles,且调用OnCached public void LoadProjcetAssetBundlesCache(string inProjectID, UnityAction <ProjectAssetBundlesInfo, string, string> OnCached = null, string hxAssetBundleName = null) { //Debug.Log("PersistentDataPath: "+Application.persistentDataPath); Loading loading = loadingManager.AddALoading(0); bool checkFile = false; if (checkFile = File.Exists(pathAndURL.localProjectAssetBundlesInfoPath)) { string log = "有本地ProjectAssetBundlesInfo.txt"; GlobalDebug.Addline(log); Debug.Log(log); string jsonStr = File.ReadAllText(pathAndURL.localProjectAssetBundlesInfoPath); localProjectAssetBundlesInfo = JsonUtility.FromJson <ProjectAssetBundlesInfo>(jsonStr); Debug.Log(pathAndURL.serverProjectAssetBundlesInfoPath); GlobalDebug.Addline(pathAndURL.serverProjectAssetBundlesInfoPath); Debug.Log(netCtrlManager); //"?"+DateTime.Now.ToString() 添加时间防止ios读取http缓存 netCtrlManager.WebRequest( "同步AssetBundle服务器", pathAndURL.serverProjectAssetBundlesInfoPath + "?" + DateTime.Now.ToString(), loading.LoadingAnimation, (NetCtrlManager.RequestHandler r, UnityWebRequestAsyncOperation a, string info) => { Debug.Log("ServerProjectAssetBundlesInfo Load Failed!"); }, (DownloadHandler t) => { serverProjectAssetBundlesInfo = JsonUtility.FromJson <ProjectAssetBundlesInfo>(t.text); // if (globalDebug) GlobalDebug.ReplaceLine(t.text, 15); Debug.Log(t.text); string log2 = "ServerTime:" + serverProjectAssetBundlesInfo.buildTime + " LocalTime:" + localProjectAssetBundlesInfo.buildTime; GlobalDebug.Addline(log2); Debug.Log(log2); //判断两个资源的生成时间,如果时间不一样表示资源以过期,要删去旧的资源以便重新下载 if (serverProjectAssetBundlesInfo.buildTime != localProjectAssetBundlesInfo.buildTime) { string log3 = "删除老资源,替换新资源"; GlobalDebug.Addline(log3); Debug.Log(log3); File.WriteAllText(pathAndURL.localProjectAssetBundlesInfoPath, t.text); for (int i = 0; i < serverProjectAssetBundlesInfo.sceneAssetBundle.Length; i++) { Caching.ClearOtherCachedVersions(pathAndURL.projectPath + serverProjectAssetBundlesInfo.sceneAssetBundle[i], Hash128.Parse(serverProjectAssetBundlesInfo.sceneAssetBundleHash[i])); } } if (OnCached != null) { OnCached.Invoke(serverProjectAssetBundlesInfo, inProjectID, hxAssetBundleName); } else { StartLoadAssetBundle(serverProjectAssetBundlesInfo); } }, null, null ); } else { string log = "无本地ProjectAssetBundlesInfo.txt"; GlobalDebug.Addline(log); Debug.Log(log); netCtrlManager.WebRequest( "同步AssetBundle服务器", pathAndURL.serverProjectAssetBundlesInfoPath, loading.LoadingAnimation, (NetCtrlManager.RequestHandler r, UnityWebRequestAsyncOperation a, string info) => { Debug.Log("ServerProjectAssetBundlesInfo Load Failed!"); }, (DownloadHandler t) => { string log2 = "获取到Server的ProjectAssetBundlesInfo.txt"; GlobalDebug.Addline(log2); Debug.Log(log2); GlobalDebug.ReplaceLine(t.text, 15); serverProjectAssetBundlesInfo = JsonUtility.FromJson <ProjectAssetBundlesInfo>(t.text); File.WriteAllText(pathAndURL.localProjectAssetBundlesInfoPath, t.text); if (OnCached != null) { OnCached.Invoke(serverProjectAssetBundlesInfo, inProjectID, hxAssetBundleName); } else { StartLoadAssetBundle(serverProjectAssetBundlesInfo); } }, null, null ); } // if(globalDebug) GlobalDebug.ReplaceLine("HasLoaclInfo.txt:" + checkFile.ToString(), 16); }
/// <summary> /// Update manifest. /// Compare manifests and delete old cached bundles. /// Starts download of manifest asset bundle. /// Returns the manifest asset bundle downolad operation object. /// </summary> /// <param name="newManifest">Asset bundle manifest.</param> static void SetManifest(AssetBundleManifest newManifest) { if (!newManifest) { Debug.LogErrorFormat("{0}マニフェスト更新 失敗 : {1}", kLog, patch); return; } var oldManifest = AssetManager.manifest; AssetManager.manifest = newManifest; if (oldManifest) { var oldBundles = new HashSet <string>(oldManifest.GetAllAssetBundles()); var newBundles = new HashSet <string>(newManifest.GetAllAssetBundles()); // 新規 var sb = new StringBuilder(); var array = newBundles.Except(oldBundles).ToArray(); sb.AppendFormat("[Added] {0}\n", array.Length); foreach (var bundleName in array) { sb.AppendFormat(" > {0} ({1})\n", bundleName, newManifest.GetAssetBundleHash(bundleName).ToString().Substring(0, 4)); } // 削除 array = oldBundles.Except(newBundles).ToArray(); sb.AppendFormat("\n[Deleted : キャッシュは削除されます] {0}\n", array.Length); foreach (var bundleName in array) { sb.AppendFormat(" > {0} ({1})\n", bundleName, oldManifest.GetAssetBundleHash(bundleName).ToString().Substring(0, 4)); } // 更新 array = oldBundles .Intersect(newBundles) .Select(name => new { name = name, oldHash = oldManifest.GetAssetBundleHash(name), newHash = newManifest.GetAssetBundleHash(name), }) .Where(x => x.oldHash != x.newHash) .Select(x => string.Format("{0} ({1} -> {2})", x.name, x.oldHash.ToString().Substring(0, 4), x.newHash.ToString().Substring(0, 4))) .ToArray(); sb.AppendFormat("\n[Updated : 古いキャッシュは削除されます] {0}\n", array.Length); foreach (var bundleName in array) { sb.AppendLine(" > " + bundleName); } #if UNITY_2017_1_OR_NEWER // 削除 foreach (var name in oldBundles.Except(newBundles)) { UnloadAssetBundleInternal(name); Caching.ClearAllCachedVersions(name); Debug.LogFormat("{0}キャッシュ削除 : {1}", kLog, name); } // 更新 foreach (var name in newBundles) { UnloadAssetBundleInternal(name); Caching.ClearOtherCachedVersions(name, newManifest.GetAssetBundleHash(name)); Debug.LogFormat("{0}キャッシュ削除 : {1}", kLog, name); } #else foreach (var name in oldBundles.Where(newBundles.Contains)) { var oldHash = oldManifest.GetAssetBundleHash(name); var newHash = newManifest.GetAssetBundleHash(name); // The bundle has removed or changed. Need to delete cached bundle. if (oldHash != newHash) { UnloadAssetBundleInternal(name); if (Caching.IsVersionCached(name, oldHash)) { Debug.LogFormat("{0}キャッシュ削除 : {1}({2})", kLog, name, oldHash.ToString().Substring(0, 4)); var request = UnityWebRequest.GetAssetBundle(name, oldHash, uint.MaxValue); request.Send(); request.Abort(); } } } #endif Debug.LogFormat("{0}マニフェスト更新 完了 : {2}\n変更は以下の通りです:\n{1}", kLog, sb, patch); } else { var newBundles = newManifest.GetAllAssetBundles(); // 新規 var sb = new StringBuilder(); sb.AppendFormat("[Added] {0}\n", newBundles.Length); foreach (var bundleName in newBundles) { sb.AppendFormat(" > {0} ({1})\n", bundleName, newManifest.GetAssetBundleHash(bundleName).ToString().Substring(0, 4)); } Debug.LogFormat("{0}マニフェスト更新 完了 : {2}\n変更は以下の通りです:\n{1}", kLog, sb, patch); } instance.storedPatch = patch; }