/// <summary> /// Computes the amount of data needed to be downloaded for this bundle. /// </summary> /// <param name="location">The location of the bundle.</param> /// <param name="resourceManager">The object that contains all the resource locations.</param> /// <returns>The size in bytes of the bundle that is needed to be downloaded. If the local cache contains the bundle or it is a local bundle, 0 will be returned.</returns> public virtual long ComputeSize(IResourceLocation location, ResourceManager resourceManager) { var id = resourceManager == null ? location.InternalId : resourceManager.TransformInternalId(location); if (!ResourceManagerConfig.IsPathRemote(id)) { return(0); } var locHash = Hash128.Parse(Hash); #if ENABLE_CACHING if (locHash.isValid) //If we have a hash, ensure that our desired version is cached. { if (Caching.IsVersionCached(new CachedAssetBundle(BundleName, locHash))) { return(0); } return(BundleSize); } else //If we don't have a hash, any cached version will do. { List <Hash128> versions = new List <Hash128>(); Caching.GetCachedVersions(BundleName, versions); if (versions.Count > 0) { return(0); } } #endif //ENABLE_CACHING return(BundleSize); }
private IEnumerator GetAssetBundles() { if (this.currentManifest == null) { yield break; } startCount++; var list = this.currentManifest.GetAllAssetBundles(); foreach (var asset in list) { //to compare them with cached version List <Hash128> listOfCachedVersions = new List <Hash128>(); Caching.GetCachedVersions(asset, listOfCachedVersions); var currentHash = this.currentManifest.GetAssetBundleHash(asset); var co = StartCoroutine(this.GetBundle(asset, currentHash)); this.currentDownloads.Add(co); yield return(co); } //Debug.LogFormat("GetAssetBundles done"); startCount--; yield return(0); }
/// <summary> /// Computes the amount of data needed to be downloaded for this bundle. /// </summary> /// <param name="loc">The location of the bundle.</param> /// <returns>The size in bytes of the bundle that is needed to be downloaded. If the local cache contains the bundle or it is a local bundle, 0 will be returned.</returns> public virtual long ComputeSize(IResourceLocation loc) { if (!loc.InternalId.Contains("://")) { return(0); } var locHash = Hash128.Parse(Hash); #if !UNITY_SWITCH && !UNITY_PS4 var bundleName = Path.GetFileNameWithoutExtension(loc.InternalId); if (locHash.isValid) //If we have a hash, ensure that our desired version is cached. { if (Caching.IsVersionCached(bundleName, locHash)) { return(0); } return(BundleSize); } else //If we don't have a hash, any cached version will do. { List <Hash128> versions = new List <Hash128>(); Caching.GetCachedVersions(bundleName, versions); if (versions.Count > 0) { return(0); } } #endif //!UNITY_SWITCH && !UNITY_PS4 return(BundleSize); }
IEnumerator GetAssetBundle() { using (UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(URL + affix, 2, 0)) { var req = uwr.SendWebRequest(); while (!req.isDone) { Debug.Log(uwr.downloadProgress); yield return(null); } ; if (uwr.isNetworkError || uwr.isHttpError) { Debug.Log(uwr.error); yield break; } var bundle = DownloadHandlerAssetBundle.GetContent(uwr); List <Hash128> listOfCachedVersions = new List <Hash128>(); Caching.GetCachedVersions(bundle.name, listOfCachedVersions); foreach (var ele in bundle.GetAllAssetNames()) { var rBundle = bundle.LoadAssetAsync(ele); var texture = rBundle.asset as Texture2D; SampleObject.GetComponent <Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero); yield return(new WaitForSeconds(0.5f)); } }; }
public void TestDownloadCachedAsset(string error, AssetBundle bundle) { List <Hash128> cachedVersions = new List <Hash128>(); Caching.GetCachedVersions(bundle.name, cachedVersions); Assert.IsTrue(bundle.Contains(TestConstants.SAMPLE_PREFAB)); Assert.AreEqual(cachedVersions.Count, 1); AssetBundle.UnloadAllAssetBundles(true); bool cleared = Caching.defaultCache.ClearCache(); }
public bool IsCached(string bundleId) { if (!Catalog.ContainsEntry(bundleId)) { return(false); } var list = new List <Hash128>(); Caching.GetCachedVersions(bundleId, list); return(list.Count > 0); }
public async UniTask <AssetBundle> LoadCachedBundle(string bundleId) { if (LoadedBundles.ContainsKey(bundleId)) { LoadedBundles[bundleId].RefCount++; return(LoadedBundles[bundleId].AssetBundle); } Debug.Log($"[BundleManager] Requested cached bundle {bundleId}"); Debug.Log($"[BundleManager] Version: {Catalog.GetEntry(bundleId).version}"); if (!IsCached(bundleId)) { return(null); } UnityWebRequest request; if (IsUpToDate(bundleId)) { Debug.Log($"[BundleManager] Cached bundle matches version"); // Use latest version request = UnityWebRequestAssetBundle.GetAssetBundle(bundleId, Catalog.GetEntry(bundleId).version, 0U); } else { // Use any existing version var list = new List <Hash128>(); Caching.GetCachedVersions(bundleId, list); Debug.Log($"[BundleManager] Cached bundle does not match version. Using {list.Last()}..."); request = UnityWebRequestAssetBundle.GetAssetBundle(bundleId, list.Last()); } using (request) { await request.SendWebRequest(); if (request.isNetworkError || request.isHttpError) { Debug.LogError(request.error); return(null); } var ab = DownloadHandlerAssetBundle.GetContent(request); LoadedBundles[bundleId] = new Entry { Id = bundleId, AssetBundle = ab, RefCount = 1 }; return(ab); } }
void CheckItemsState() { itemsBought = new Dictionary <string, bool>(); foreach (ScriptableStoreItem item in storeItems.items) { //TODO:: check also if any item is bought in IAP (might not been downloaded in this phone - or even deleted?) itemsBought[item.GetThisPlatformId()] = true; // DEBUG } itemsDownloaded = new Dictionary <string, bool>(); foreach (ScriptableStoreItem item in storeItems.items) { // check if latest version is in cache, if so trigger an event (as someone will want to use it - this might be at startup) List <Hash128> cachedVersions = new List <Hash128>(); Caching.GetCachedVersions(item.bundle.GetBundleName(), cachedVersions); //Caching.GetCachedVersions("pepe", cachedVersions); string str = ""; foreach (Hash128 h in cachedVersions) { //str += h.ToString() + ", "; str += h.ToString() + " :: " + h.GetHashCode() + " :: " + h.isValid + "\n"; } Debug.Log("item " + item.bundle.GetBundleName() + "\ncachedVersions:" + str + "\nlatestHash:" + itemsLatestHash[item.GetThisPlatformId()].ToString()); bool cached = false; foreach (Hash128 cachedHash in cachedVersions) { //if (cachedVersions.Contains(itemsLatestHash[item.GetThisPlatformId()])) if (cachedHash == itemsLatestHash[item.GetThisPlatformId()]) { Debug.Log("latest is in cache"); itemsDownloaded[item.GetThisPlatformId()] = true; cached = true; } //else } if (!cached) { Debug.Log("version available to download"); itemsDownloaded[item.GetThisPlatformId()] = false; } } itemsAsset = new Dictionary <string, Object>(); }
public static int GetCachedVersions_s(IntPtr l) { int result; try { string assetBundleName; LuaObject.checkType(l, 1, out assetBundleName); List <Hash128> outCachedVersions; LuaObject.checkType <List <Hash128> >(l, 2, out outCachedVersions); Caching.GetCachedVersions(assetBundleName, outCachedVersions); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return(result); }
/// <inheritdoc/> public override long ComputeSize(IResourceLocation location, ResourceManager resourceManager) { var id = resourceManager == null ? location.InternalId : resourceManager.TransformInternalId(location); if (!ResourceManagerConfig.IsPathRemote(id)) { return(0); } var locHash = Hash128.Parse(Hash); if (!locHash.isValid) { return(BundleSize); } #if !UNITY_SWITCH && !UNITY_PS4 var bundleName = Path.GetFileNameWithoutExtension(id); if (locHash.isValid) //If we have a hash, ensure that our desired version is cached. { if (Caching.IsVersionCached(bundleName, locHash)) { return(0); } return(BundleSize); } else //If we don't have a hash, any cached version will do. { List <Hash128> versions = new List <Hash128>(); Caching.GetCachedVersions(bundleName, versions); if (versions.Count > 0) { return(0); } } #endif //!UNITY_SWITCH && !UNITY_PS4 return(BundleSize); }
/// <summary> /// Computes the amount of data needed to be downloaded for this bundle. /// </summary> /// <param name="loc">The location of the bundle.</param> /// <returns>The size in bytes of the bundle that is needed to be downloaded. If the local cache contains the bundle or it is a local bundle, 0 will be returned.</returns> public override long ComputeSize(IResourceLocation loc) { if (!loc.InternalId.Contains("://")) { // Debug.LogFormat("Location {0} is local, ignoring size", loc); return(0); } var locHash = Hash128.Parse(Hash); if (!locHash.isValid) { // Debug.LogFormat("Location {0} has invalid hash, using size of {1}", loc, BundleSize); return(BundleSize); } #if !UNITY_SWITCH && !UNITY_PS4 var bundleName = Path.GetFileNameWithoutExtension(loc.InternalId); if (locHash.isValid) //If we have a hash, ensure that our desired version is cached. { if (Caching.IsVersionCached(bundleName, locHash)) { return(0); } return(BundleSize); } else //If we don't have a hash, any cached version will do. { List <Hash128> versions = new List <Hash128>(); Caching.GetCachedVersions(bundleName, versions); if (versions.Count > 0) { return(0); } } #endif //!UNITY_SWITCH && !UNITY_PS4 return(BundleSize); }
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 } } }
public static IEnumerator loadBundle(Enums.AssetBundleIdentifiers bundleIdentifier, UnityAction <AssetBundle> callback, UnityAction <UnityWebRequest> downloadProgress, bool shouldBeCached) { string platformBundleName = bundleIdentifier.ToString().ToLower(); #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX platformBundleName += "-Mac"; #elif UNITY_ANDROID platformBundleName += "-Android"; #elif UNITY_IOS platformBundleName += "-IOS"; #elif UNITY_STANDALONE_LINUX platformBundleName += "-Linux"; #endif List <Hash128> cachedVersions = new List <Hash128>(); Caching.GetCachedVersions(platformBundleName, cachedVersions); Hash128 versionCheckHash = Hash128.Compute(AssetBundleManager.getAssetBundleVersion(bundleIdentifier).ToString()); if (!cachedVersions.Contains(versionCheckHash) && shouldBeCached) { Debug.LogError("============="); Debug.LogError("Asset bundle: '" + platformBundleName + "' should have been cached, but isn't."); Debug.LogError("============="); } if (!cachedVersions.Contains(versionCheckHash) && AssetBundleManager.getAssetBundle(bundleIdentifier) != null) { Debug.Log("Removing old asset bundle version from cache."); AssetBundleManager.removeAssetBundle(bundleIdentifier); } string bundleUrl = bundleBaseUrl + platformBundleName; Debug.Log("Bundle URL: " + bundleUrl); UnityWebRequest req = UnityWebRequestAssetBundle.GetAssetBundle(bundleUrl, versionCheckHash, 0); if (downloadProgress != null) { downloadProgress(req); } yield return(req.SendWebRequest()); if (req.isNetworkError) { Debug.LogError("Network error. " + req.responseCode); } else { if (AssetBundleManager.getAssetBundle(bundleIdentifier) != null) { Debug.Log("Asset bundle loaded from memory!"); callback(AssetBundleManager.getAssetBundle(bundleIdentifier)); } else { AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(req); if (assetBundle != null) { Debug.Log("Asset bundle loaded!"); AssetBundleManager.addAssetBundle(bundleIdentifier, assetBundle); callback(assetBundle); } else { Debug.LogError("BUNDLE IS NULL"); } } } }
/// <summary> /// 下载服务器的ABConfig.json与本地ABConfig.json对比差异,有差异则下载更新 /// </summary> /// <returns></returns> private IEnumerator DoCheckUpdate(Action <Dictionary <string, SingleBundleInfo> > onFinished) { string abConfigUrl = _baseURL + "ABConfig.json"; UnityWebRequest request = UnityWebRequest.Get(abConfigUrl); yield return(request.SendWebRequest()); if (request.error != null) { LogUtil.LogError($"下载AssetBundle版本文件时发生错误,url:{abConfigUrl},error:{request.error}"); yield break; } _serverABConfig = request.downloadHandler.text; request.Dispose(); Debug.Log("下载AssetBundle的版本文件:\n" + _serverABConfig); var serverAllBundleInfo = JsonConvert.DeserializeObject <AllBundleInfo>(_serverABConfig); if (serverAllBundleInfo == null) { LogUtil.LogError("下载AssetBundle版本文件解析出来是空值!"); yield break; } string streamingAssetsABconfigPath = Application.streamingAssetsPath + "/ABconfig.json";//本地路径 if (!File.Exists(streamingAssetsABconfigPath)) { LogUtil.LogError("streamingAssetsPath文件夹没有ABconfig.json文件!"); yield break; } //缓存文件夹没有 ABconfig.json ,则从 streamingAssetsPath 文件下拷贝过去 string persistentABconfigPath = Application.persistentDataPath + "/ABconfig.json";//缓存路径 if (!File.Exists(persistentABconfigPath)) { FileInfo fileInfo = new FileInfo(streamingAssetsABconfigPath); fileInfo.CopyTo(persistentABconfigPath); Debug.Log("成功从“streamingAssetsPath”拷贝ABconfig.json到“persistentDataPath”!"); } else { Debug.Log("“persistentDataPath”路径下存在ABconfig.json文件!"); } //打开缓存的 ABconfig.json,比较差别,检测是否需要更新 string abConfig = FileHelper.ReadStrFromFile(persistentABconfigPath, false); var localAllBundleInfo = JsonConvert.DeserializeObject <AllBundleInfo>(abConfig); if (localAllBundleInfo == null) { LogUtil.LogError("缓存文件夹下ABconfig.json文件格式错误!"); yield break; } Debug.Log("本地AssetBundle版本文件:\n" + JsonConvert.SerializeObject(localAllBundleInfo, Formatting.Indented)); //获取需要更新的assetbundle。 Dictionary <string, SingleBundleInfo> changedDic = GetChangedBundleInfo(serverAllBundleInfo.BundleInfoList, localAllBundleInfo.BundleInfoList); foreach (var item in changedDic) { List <Hash128> lis = new List <Hash128>(); Caching.GetCachedVersions(item.Value.bundleName, lis); foreach (var hash128 in lis) { Debug.Log(string.Format("AssetBundle:{0},hash128:{1}", item.Value.bundleName, hash128)); } } Debug.Log(string.Format("需要更新的资源有{0}个,列表如下:", changedDic.Count)); foreach (var item in changedDic) { Debug.Log(item.Value.bundleName); } //没有资源更新的情况 if (changedDic.Count == 0) { InitBasicData(); } onFinished?.Invoke(changedDic); }
//public void LoadFromLocal() //{ // string path = ""; // path = "file://" + Application.persistentDataPath + "/ar-exp-saltbrochure-android"; // //path = "file://" + "C:/Users/sricciardi/Desktop/Projects/AR Projects/Salt-Generic-AR-App/Assets/AssetBundles/Android" + "/ar-exp-saltbrochure-android"; // Debug.Log(path); // StartCoroutine(LoadFromMemoryAsync(path)); //} IEnumerator DownloadAndCacheAB(string bundleURLPath, string manifestURLBundlePath) { //AssetBundle manifestBundle = AssetBundle.LoadFromFile(manifestBundlePath); //AssetBundleManifest manifest = manifestBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest"); string editorManifestFilePath = Application.dataPath + "/AssetBundles/Android/" + ABFileName + ".manifest"; string manifestFilePath = Path.Combine(Application.persistentDataPath, ABmanifestFileName); string bundleFilePath = Path.Combine(Application.persistentDataPath, ABFileName); Debug.Log("Unity Editor manifest path " + editorManifestFilePath); if (Application.isEditor) { DHmanifest = new DownloadHandlerFile(editorManifestFilePath); Debug.Log("I am running in the Unity Editor!"); } else { DHmanifest = new DownloadHandlerFile(manifestFilePath); } //DownloadHandlerFile dh = new DownloadHandlerFile(filePath); //DownloadHandlerAssetBundle DHAB = new DownloadHandlerAssetBundle(bundleFilePath); //DownloadHandler DHmanifest = new DownloadHandlerFile(manifestFilePath); // Correct! UWRmanifest = UnityWebRequest.Get(manifestURLBundlePath); //UWRbundle = UnityWebRequestAssetBundle.GetAssetBundle(bundleURLPath); //uwr.downloadHandler = dhAB; UWRmanifest.downloadHandler = DHmanifest; yield return(UWRmanifest.SendWebRequest()); //UWRbundle.downloadHandler = DHAB; //yield return UWRbundle.SendWebRequest(); //uwr.downloadHandler = dh; //yield return uwr.SendWebRequest(); if (UWRmanifest.isNetworkError || UWRmanifest.isHttpError) { Debug.Log("Network error trying to retrieve the manifest file!"); } else { Debug.Log("There was no Network error, so try to load the Asset Bundle from the local file"); AssetBundle manifestBundle = AssetBundle.LoadFromFile(manifestFilePath); 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(ABFileName); UnityWebRequest UWRbundleRequest = UnityWebRequestAssetBundle.GetAssetBundle(bundleURLPath, hash, 0); yield return(UWRbundleRequest.SendWebRequest()); AssetBundle UWRbundle = DownloadHandlerAssetBundle.GetContent(UWRbundleRequest); //Get all the cached versions List <Hash128> listOfCachedVersions = new List <Hash128>(); Caching.GetCachedVersions(UWRbundle.name, listOfCachedVersions); if (!AssetBundleContainsAssetIWantToLoad(UWRbundle)) { Caching.currentCacheForWriting = Caching.GetCacheAt(Caching.cacheCount); Caching.RemoveCache(newCache); Debug.Log("There is no Scene in the downloaded Asset Bundle."); for (int i = listOfCachedVersions.Count - 1; i > 0; i--) { //Load a different bundle from a different cache. UWRbundleRequest = UnityWebRequestAssetBundle.GetAssetBundle(bundleURLPath, listOfCachedVersions[i], 0); yield return(UWRbundleRequest.SendWebRequest()); UWRbundle = DownloadHandlerAssetBundle.GetContent(UWRbundleRequest); //Check and see if the newly loaded bundle from the cache meets your criteria. if (AssetBundleContainsAssetIWantToLoad(UWRbundle)) { //This is where I need to load the scene the correct way. break; } } } else { Debug.Log("I found the scene I am looking for in the downloaded version."); } } /* * if (uwr.isNetworkError || uwr.isHttpError) * { * Debug.Log(uwr.error); * } else * { * //Get Asset Bundle * AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr); * * isLoading = true; * * if (uwr.isDone) * { * * //AssetBundleManifest manifest = bundle.LoadAsset<AssetBundleManifest>(bundle.name); * Debug.Log("bundle name " + bundle.name); * Debug.Log("is Streamed Asset Bundle " + bundle.isStreamedSceneAssetBundle); * } * * * //AssetBundle manifestBundle = AssetBundle.LoadFromFile(manifestBundlePath); * //AssetBundleManifest manifest = bundle.LoadAssetAsync<AssetBundleManifest>(ABFileName); * //Debug.Log("manifest " + manifest); * * string[] assetBundlePaths = bundle.GetAllScenePaths(); * * if (assetBundlePaths != null) { * * //AssetBundleLoadOperation request = AssetBundleManager.LoadLevelAsync(sceneAssetBundle, levelName, isAdditive); * //if (request == null) * // yield break; * //yield return StartCoroutine(request); * * for (int i = 0; i < assetBundlePaths.Length; i++) * { * Debug.Log("string # " + i + " is " + assetBundlePaths[i]); * } * } */ //string filePath = Path.Combine(Application.persistentDataPath, ABFileName); //DownloadHandlerFile dh = new DownloadHandlerFile(filePath); //UnityWebRequest requestFile = UnityWebRequest.Get(url); //requestFile.downloadHandler = dh; //yield return requestFile.SendWebRequest(); //if (!requestFile.isHttpError && !requestFile.isNetworkError) //{ // Debug.Log("Download complete, attempting to load bundle."); // AssetBundle bundleFile = AssetBundle.LoadFromFile(filePath); // SceneManager.LoadScene(bundleFile.GetAllScenePaths()[0]); //} //else //{ // Debug.LogError(requestFile.responseCode + ": " + requestFile.error); //} // Load level from assetBundle. ////AssetBundleRequest asset = bundle.LoadAssetAsync<AssetBundleManifest>(ABFileName); //AssetBundleRequest asset = bundle.LoadAsset<AssetBundleManifest>(ABFileName); //yield return asset; ////Get the Asset Bundle Manifest //AssetBundleManifest loadedAssetMf = asset.asset as AssetBundleManifest; ////Get Hash128 from the AssetBundleManifest //Hash128 tempHash128 = loadedAssetMf.GetAssetBundleHash(ABFileName); ////Pass to the isVersionCached function //if (Caching.IsVersionCached(bundlePath, tempHash128)) //{ // isCached = true; // Debug.Log("Bundle is Cached"); //} else //{ // isLoading = true; // Debug.Log("Bundle is Downloading...."); //} ////Caching.IsVersionCached(bundlePath, tempHash128); }