private IEnumerator LoadResource(string resourcePath, string resourceName) { if (string.IsNullOrEmpty(resourcePath) || string.IsNullOrEmpty(resourceName)) { MyLog.ErrorWithFrame(name, "加载资源失败 resourcePath = " + resourcePath + " resourceName = " + resourceName); yield break; } //避免同一个assetbundle 同一时间多次下载 if (_assetBundleCache.ContainsKey(resourcePath)) { yield break; } _assetBundleCache.Add(resourcePath, null); MyLog.InfoWithFrame(name, "加载资源 :" + resourcePath); var config = _context.GetConfigHolder(); var baseVersion = config.ResourceVersion; if (_manifest == null) { var lastManifestAssetVersion = GetLastAssetVersion("StreamingAssets"); var manifestPath = lastManifestAssetVersion == null ? Path.Combine(StreamingAssetsPath, "StreamingAssets") : lastManifestAssetVersion.Url; var manifestVersion = lastManifestAssetVersion == null ? baseVersion : lastManifestAssetVersion.Version; using (var manifestReq = UnityWebRequest.GetAssetBundle( manifestPath, (uint)manifestVersion, (uint)0)) { manifestReq.SendWebRequest(); while (!manifestReq.isDone) { yield return(null); } if (manifestReq.isNetworkError || manifestReq.isHttpError) { MyLog.ErrorWithFrame(name, "加manifest失败 resourcePath = " + resourcePath + " resourceName = " + resourceName + " error " + manifestReq.error + " manifestPath = " + manifestPath); yield break; } var manifestBundle = DownloadHandlerAssetBundle.GetContent(manifestReq); if (manifestBundle == null) { MyLog.ErrorWithFrame(name, "加载manifest失败 resourcePath = " + resourcePath + " resourceName = " + resourceName + " manifestPath = " + manifestPath); yield break; } var manifest = manifestBundle.LoadAsset <AssetBundleManifest>("AssetBundleManifest"); manifestBundle.Unload(false); if (manifest == null) { MyLog.ErrorWithFrame(name, "加载manifest失败 resourcePath = " + resourcePath + " resourceName = " + resourceName + " manifest == null" + " manifestPath = " + manifestPath); yield break; } _manifest = manifest; } } var dependencies = _manifest.GetAllDependencies(resourcePath); if (dependencies != null && dependencies.Length > 0) { foreach (var dep in dependencies) { if (string.IsNullOrEmpty(dep)) { continue; } if (_assetBundleCache.ContainsKey(dep)) { while (_assetBundleCache[dep] == null) { yield return(null); } continue; } _assetBundleCache.Add(dep, null); var lastDepAssetVersion = GetLastAssetVersion(dep); var depPath = lastDepAssetVersion == null ? Path.Combine(StreamingAssetsPath, dep) : lastDepAssetVersion.Url; var depVersion = lastDepAssetVersion == null ? baseVersion : lastDepAssetVersion.Version; using (var depReq = UnityWebRequest.GetAssetBundle( depPath, (uint)depVersion, (uint)0)) { depReq.SendWebRequest(); while (!depReq.isDone) { yield return(null); } if (depReq.isNetworkError || depReq.isHttpError) { MyLog.ErrorWithFrame(name, "加载依赖资源失败 resourcePath = " + resourcePath + "resourceName = " + resourceName + " " + depReq.error); yield break; } var depBundle = DownloadHandlerAssetBundle.GetContent(depReq); if (depBundle == null) { MyLog.ErrorWithFrame(name, "加载依赖资源失败 resourcePath = " + resourcePath + "resourceName = " + resourceName); yield break; } if (_assetBundleCache.ContainsKey(dep)) { _assetBundleCache[dep] = depBundle; } else { _assetBundleCache.Add(dep, depBundle); } } } } var lastAssetVersion = GetLastAssetVersion(resourcePath); var path = lastAssetVersion == null ? Path.Combine(StreamingAssetsPath, resourcePath) : lastAssetVersion.Url; var version = lastAssetVersion == null ? baseVersion : lastAssetVersion.Version; using (var abReq = UnityWebRequest.GetAssetBundle( path, (uint)version, (uint)0)) { abReq.SendWebRequest(); while (!abReq.isDone) { yield return(null); } if (abReq.isNetworkError || abReq.isHttpError) { MyLog.ErrorWithFrame(name, "加载资源失败 resourcePath = " + resourcePath + " resourceName = " + resourceName + " " + abReq.error); yield break; } var assetBundle = DownloadHandlerAssetBundle.GetContent(abReq); if (assetBundle == null) { MyLog.ErrorWithFrame(name, "加载资源失败 resourcePath = " + resourcePath + " resourceName = " + resourceName); yield break; } if (_assetBundleCache.ContainsKey(resourcePath)) { _assetBundleCache[resourcePath] = assetBundle; } else { _assetBundleCache.Add(resourcePath, assetBundle); } } }
public override AssetBundle GetContent(UnityWebRequest request) { Result = DownloadHandlerAssetBundle.GetContent(request); return(Result); }
//异步加载资源 private IEnumerator LoadAssetAsync <T>(ResourceInfoBase info, HTFAction <float> loadingAction, HTFAction <T> loadDoneAction, bool isPrefab = false, Transform parent = null, bool isUI = false) where T : UnityEngine.Object { DateTime beginTime = DateTime.Now; if (_isLoading) { yield return(_loadWait); } _isLoading = true; yield return(Main.Current.StartCoroutine(LoadDependenciesAssetBundleAsync(info.AssetBundleName))); DateTime waitTime = DateTime.Now; UnityEngine.Object asset = null; if (Mode == ResourceLoadMode.Resource) { ResourceRequest request = Resources.LoadAsync <T>(info.ResourcePath); while (!request.isDone) { loadingAction?.Invoke(request.progress); yield return(null); } asset = request.asset; if (asset) { if (isPrefab) { asset = ClonePrefab(asset as GameObject, parent, isUI); } } else { throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:Resources文件夹中不存在资源 " + info.ResourcePath + "!"); } } else { #if UNITY_EDITOR if (IsEditorMode) { loadingAction?.Invoke(1); yield return(null); asset = AssetDatabase.LoadAssetAtPath <T>(info.AssetPath); if (asset) { if (isPrefab) { asset = ClonePrefab(asset as GameObject, parent, isUI); } } else { throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:路径中不存在资源 " + info.AssetPath + "!"); } } else { if (_assetBundles.ContainsKey(info.AssetBundleName)) { loadingAction?.Invoke(1); yield return(null); asset = _assetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath); if (asset) { if (isPrefab) { asset = ClonePrefab(asset as GameObject, parent, isUI); } } else { throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !"); } } else { using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(_assetBundleRootPath + info.AssetBundleName, GetAssetBundleHash(info.AssetBundleName))) { request.SendWebRequest(); while (!request.isDone) { loadingAction?.Invoke(request.downloadProgress); yield return(null); } if (!request.isNetworkError && !request.isHttpError) { AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request); if (bundle) { asset = bundle.LoadAsset <T>(info.AssetPath); if (asset) { if (isPrefab) { asset = ClonePrefab(asset as GameObject, parent, isUI); } } else { throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !"); } if (IsCacheAssetBundle) { if (!_assetBundles.ContainsKey(info.AssetBundleName)) { _assetBundles.Add(info.AssetBundleName, bundle); } } else { bundle.Unload(false); } } else { throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!"); } } else { throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!"); } } } } #else if (_assetBundles.ContainsKey(info.AssetBundleName)) { loadingAction?.Invoke(1); yield return(null); asset = _assetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath); if (asset) { if (isPrefab) { asset = ClonePrefab(asset as GameObject, parent, isUI); } } else { throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !"); } } else { using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(_assetBundleRootPath + info.AssetBundleName, GetAssetBundleHash(info.AssetBundleName))) { request.SendWebRequest(); while (!request.isDone) { loadingAction?.Invoke(request.downloadProgress); yield return(null); } if (!request.isNetworkError && !request.isHttpError) { AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request); if (bundle) { asset = bundle.LoadAsset <T>(info.AssetPath); if (asset) { if (isPrefab) { asset = ClonePrefab(asset as GameObject, parent, isUI); } } else { throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !"); } if (IsCacheAssetBundle) { if (!_assetBundles.ContainsKey(info.AssetBundleName)) { _assetBundles.Add(info.AssetBundleName, bundle); } } else { bundle.Unload(false); } } else { throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!"); } } else { throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!"); } } } #endif } DateTime endTime = DateTime.Now; GlobalTools.LogInfo(string.Format("异步加载资源{0}[{1}模式]:\r\n{2}\r\n等待耗时:{3}秒 加载耗时:{4}秒", asset ? "成功" : "失败", Mode , Mode == ResourceLoadMode.Resource ? info.GetResourceFullPath() : info.GetAssetBundleFullPath(_assetBundleRootPath) , (waitTime - beginTime).TotalSeconds, (endTime - waitTime).TotalSeconds)); if (asset) { DataSetInfo dataSet = info as DataSetInfo; if (dataSet != null && dataSet.Data != null) { asset.Cast <DataSetBase>().Fill(dataSet.Data); } loadDoneAction?.Invoke(asset as T); } asset = null; _isLoading = false; }
//public Text Status; /*private void Awake() * { * instance = this; * }*/ public IEnumerator getmodelfromazure() { //Status.text = "已點擊"; yield return(new WaitForSeconds(2f)); var uwr = UnityWebRequestAssetBundle.GetAssetBundle("https://firebasestorage.googleapis.com/v0/b/hui0414-b2e18.appspot.com/o/1fv1?alt=media&token=8fa83e64-03d6-4e60-8264-3ceb4cf9adc7"); yield return(uwr.SendWebRequest()); // Get an asset from the bundle and instantiate it. AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr); //var loadAsset = bundle.LoadAssetAsync<GameObject>("Assets/Players/MainPlayer.prefab"); var loadAsset = bundle.LoadAsset("1fv1"); yield return(loadAsset); //Instantiate(loadAsset.asset); //Instantiate(loadAsset); //if (Instantiate(loadAsset)) = true; //yield return new WaitForSeconds(2f); go1 = Instantiate(loadAsset) as GameObject; go1.transform.parent = GameObject.Find("ModelManager").transform; // Status.text = "已顯示Cube"; //Getrender(go1); GetChildmesh(go1); SplitList(go1); setposition(go1); Getread(go1); Getamountinfo(go1); addworkitem(go1); Getclickapp(go1); //GetChildRecursive(go1); rotationaxis(go1); Manipulator(go1); Cursorcontextinfo(go1); Cursorcontext(go1); Debug.Log("123"); MinMaxScale(go1); getbound(go1); grabbable(go1); renewcolor.Loadmtl = 1; if (GameObject.Find("1fpipe(Clone)") != null) { GameObject.Find("1fpipe(Clone)").transform.SetParent(go1.transform); } if (GameObject.Find("drainpipe(Clone)") != null) { GameObject.Find("drainpipe(Clone)").transform.SetParent(go1.transform); } GameObject.Find("922434").GetComponent <readdata>().work01 = "N02輕隔間-雙面單層輕隔間,4米以下"; GameObject.Find("922434").GetComponent <readdata>().Object = "基本牆"; GameObject.Find("922434").GetComponent <readdata>().level = "1F"; GameObject.Find("1046217").GetComponent <readdata>().work01 = "S01水泥砂漿粉刷工程"; GameObject.Find("1046217").GetComponent <readdata>().work02 = "S02油漆工程"; GameObject.Find("1046217").GetComponent <readdata>().Object = "基本牆"; GameObject.Find("1046217").GetComponent <readdata>().level = "1F"; //GameObject.Find("764816").GetComponent<readdata>().work01 = "S01水泥砂漿粉刷工程"; /* GameObject.Find("764816").GetComponent<readdata>().work02 = "S02油漆工程"; * GameObject.Find("764816").GetComponent<readdata>().Object = "樓板"; * GameObject.Find("764816").GetComponent<readdata>().level = "1F";*/ GameObject.Find("768845").GetComponent <readdata>().work01 = "S01水泥砂漿粉刷工程"; GameObject.Find("768845").GetComponent <readdata>().work02 = "S02油漆工程"; GameObject.Find("768845").GetComponent <readdata>().Object = "M_混凝土-矩形-柱"; GameObject.Find("768845").GetComponent <readdata>().level = "1F"; // SendMessage("okokokgo"); //順序很重要 }
public override IEnumerator DoLoadAsync(System.Action finishCallback) { //开启的时候已经结束了 if (RefCount <= 0) { OnResLoadFaild(); finishCallback(); yield break; } if (AssetBundlePathHelper.SimulationMode) { yield return(null); } else { var url = AssetBundleSettings.AssetBundleName2Url(mAssetName); if (FromUnityToDll.Platform.IsWebGL) { var abcR = UnityWebRequestAssetBundle.GetAssetBundle(url); var request = abcR.SendWebRequest(); mAssetBundleCreateRequest = request; yield return(request); mAssetBundleCreateRequest = null; if (!request.isDone) { Log.E("AssetBundleCreateRequest Not Done! Path:" + mAssetName); OnResLoadFaild(); finishCallback(); yield break; } var ab = DownloadHandlerAssetBundle.GetContent(abcR); AssetBundle = ab; // 销毁 abcR.Dispose(); } else { var abcR = AssetBundle.LoadFromFileAsync(url); mAssetBundleCreateRequest = abcR; yield return(abcR); mAssetBundleCreateRequest = null; if (!abcR.isDone) { Log.E("AssetBundleCreateRequest Not Done! Path:" + mAssetName); OnResLoadFaild(); finishCallback(); yield break; } AssetBundle = abcR.assetBundle; } } State = ResState.Ready; finishCallback(); }
// サーバからアセットバンドルをダウンロードする private static IEnumerator Download(string[] assetBundleNames, OnDownloadProgressUpdate update) { // キャッシュできる状態か確認 while (!Caching.ready) { yield return(null); } // アセットバンドルを全てダウンロードするまで回す fileIndex = 0; do { // baseURLにAssetBuddle名を付与してURL生成 string bundleName = assetBundleNames[fileIndex]; string url = baseURL + bundleName; string manifestURL = url + ".manifest"; // URLキャッシュ防止のためタイムスタンプを付与 url += ((url.Contains("?")) ? "&" : "?") + "t=" + DateTime.Now.ToString("yyyyMMddHHmmss"); manifestURL += ((manifestURL.Contains("?")) ? "&" : "?") + "t=" + DateTime.Now.ToString("yyyyMMddHHmmss"); // CRCチェックを行うか確認 // manifestファイルをDL UnityWebRequest wwwManifest = UnityWebRequest.Get(manifestURL); // ダウンロードを待つ yield return(wwwManifest.SendWebRequest()); // manifestが存在していた場合はCRCチェックをする uint latestCRC = 0; if (string.IsNullOrEmpty(wwwManifest.error)) { // manifest内部のCRCコードを抽出する string[] lines = wwwManifest.downloadHandler.text.Split(new string[] { "CRC: " }, StringSplitOptions.None); latestCRC = uint.Parse(lines[1].Split(new string[] { "\n" }, StringSplitOptions.None)[0]); #if UNITY_2017_1_OR_NEWER // キャッシュを個別削除する string key = "km_assetbundleversioncache_" + bundleName; if (PlayerPrefs.HasKey(key)) { string currentCRC = PlayerPrefs.GetString(key); if (currentCRC != latestCRC.ToString()) { PlayerPrefs.SetString(key, latestCRC.ToString()); // 新しいcrcを保存 Caching.ClearAllCachedVersions(bundleName); // 既存のキャッシュを削除 } Debug.Log("[" + bundleName + ".manifest] \n" + "Latest CRC : " + latestCRC + " Current CRC: " + currentCRC); } else { PlayerPrefs.SetString(key, latestCRC.ToString()); // 新しいcrcを保存 } latestCRC = 0; #endif } else { Debug.Log(bundleName + ".manifest has not found."); } // CRCチェックしてダウンロード開始 using (UnityWebRequest www = UnityWebRequest.GetAssetBundle(url, ver, latestCRC)) { // ダウンロード開始 www.SendWebRequest(); // ダウンロードが完了するまでプログレスを更新する while (www.downloadProgress < 1f) { // progress設定 float progress = 0f; if (www.downloadProgress > 0) { progress = www.downloadProgress; } // 更新する update(progress, fileIndex, false, www.error); yield return(new WaitForEndOfFrame()); } // エラー処理 if (!string.IsNullOrEmpty(www.error)) { // 完了通知 update(0f, fileIndex, false, www.error); string err = www.error; Debug.Log(www.error); // wwwを解放する www.Dispose(); throw new Exception("WWW download had an error:" + err); } // ロードしたアセットバンドルをセット AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www); // AssetBundle内部に同名のCRYPTO_SIGNがあった場合、暗号化Assetと判断して復号する if (bundle.Contains(CRYPTO_SIGN + bundle.name)) { bundle = DecryptingAssetBundle(bundle); yield return(bundle); } bundleDic.Add(bundleName, bundle); // wwwを解放する www.Dispose(); } } while (++fileIndex < assetBundleNames.Length); // 完了通知 update(1f, fileIndex, true, null); }
IEnumerator Run() { _started = true; LoadItem item = null; while (true) { if (_items.Count > 0) { item = _items[0]; _items.RemoveAt(0); } else { break; } if (_pool.ContainsKey(item.url)) { //Debug.Log("hit " + item.url); NTexture texture = (NTexture)_pool[item.url]; texture.refCount++; if (item.onSuccess != null) { item.onSuccess(texture); } continue; } string url = _basePath + item.url + ".ab"; #if UNITY_2017_2_OR_NEWER #if UNITY_2018_1_OR_NEWER UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(url); #else UnityWebRequest www = UnityWebRequest.GetAssetBundle(url); #endif yield return(www.SendWebRequest()); if (!www.isNetworkError && !www.isHttpError) { AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www); #else WWW www = new WWW(url); yield return(www); if (string.IsNullOrEmpty(www.error)) { AssetBundle bundle = www.assetBundle; #endif if (bundle == null) { Debug.LogWarning("Run Window->Build FairyGUI example Bundles first."); if (item.onFail != null) { item.onFail(www.error); } continue; } #if (UNITY_5 || UNITY_5_3_OR_NEWER) NTexture texture = new NTexture(bundle.LoadAllAssets <Texture2D>()[0]); #else NTexture texture = new NTexture((Texture2D)bundle.mainAsset); #endif texture.refCount++; bundle.Unload(false); _pool[item.url] = texture; if (item.onSuccess != null) { item.onSuccess(texture); } } else { if (item.onFail != null) { item.onFail(www.error); } } } _started = false; } IEnumerator FreeIdleIcons() { yield return(new WaitForSeconds(POOL_CHECK_TIME)); //check the pool every 30 seconds int cnt = _pool.Count; if (cnt > MAX_POOL_SIZE) { ArrayList toRemove = null; foreach (DictionaryEntry de in _pool) { string key = (string)de.Key; NTexture texture = (NTexture)de.Value; if (texture.refCount == 0) { if (toRemove == null) { toRemove = new ArrayList(); } toRemove.Add(key); texture.Dispose(); //Debug.Log("free icon " + de.Key); cnt--; if (cnt <= 8) { break; } } } if (toRemove != null) { foreach (string key in toRemove) { _pool.Remove(key); } } } } }
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 DownloadBundle(AssetBundleMeta meta, Action <AssetBundle> response = default) { State = StateDownload.None; while (!Caching.ready) { yield return(null); } hash = Hash128.Parse(meta.Name); if (DownloadResourseManager.AllAssets.ContainsKey(meta)) { State = StateDownload.Success; response?.Invoke(DownloadResourseManager.AllAssets[meta]); OnDownloaded?.Invoke(); Debug.Log($"Load from Memory <color=green>{meta.Name}</color>."); } using (uwr = UnityWebRequest.Head(meta.Url)) { async = uwr.SendWebRequest(); while (!async.isDone && string.IsNullOrEmpty(uwr.error)) { yield return(null); } State = string.IsNullOrEmpty(uwr.error) ? StateDownload.Success : StateDownload.Error; if (State == StateDownload.Error) { using (uwr = UnityWebRequestAssetBundle.GetAssetBundle(meta.Url, hash)) { async = uwr.SendWebRequest(); while (!async.isDone && string.IsNullOrEmpty(uwr.error)) { yield return(null); } State = string.IsNullOrEmpty(uwr.error) ? StateDownload.Success : StateDownload.Error; if (State == StateDownload.Error) { OnError?.Invoke(uwr); Debug.Log($"{uwr.responseCode}\n" + $"<color=red>{uwr.error}</color>"); yield break; } else { AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr); if (bundle != null) { if (DownloadResourseManager.AllAssets.ContainsKey(meta)) { DownloadResourseManager.AllAssets.Remove(meta); } DownloadResourseManager.AllAssets.Add(meta, bundle); response?.Invoke(bundle); OnDownloaded?.Invoke(); Debug.Log($"Load from CACHE <color=green>{bundle.name}</color>."); } } } } else { contentLength = Convert.ToInt64(uwr.GetResponseHeader("Content-Length")); if (contentLength / Math.Pow(1024, 2) > SystemInfo.systemMemorySize) { State = StateDownload.Error; Debug.Log("<color=red>Not anough memory on device.</color>"); yield break; } } } using (uwr = UnityWebRequestAssetBundle.GetAssetBundle(meta.Url, hash)) { async = uwr.SendWebRequest(); while (!async.isDone && string.IsNullOrEmpty(uwr.error)) { yield return(null); } State = string.IsNullOrEmpty(uwr.error) ? StateDownload.Success : StateDownload.Error; if (State == StateDownload.Error) { OnError?.Invoke(uwr); Debug.Log($"{uwr.responseCode}\n" + $"<color=red>{uwr.error}</color>"); yield break; } else { AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr); if (bundle != null) { if (DownloadResourseManager.AllAssets.ContainsKey(meta)) { DownloadResourseManager.AllAssets.Remove(meta); } DownloadResourseManager.AllAssets.Add(meta, bundle); response?.Invoke(bundle); OnDownloaded?.Invoke(); } } } }
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"); } } } }
public IEnumerator LoadAssetAsync(BaseResourcesInfo resInfo, Action <float> loadingProcess, Action <UnityEngine.Object> loadedSuccess) { DateTime beginTime = DateTime.Now; // if (isLoading) // yield return waitUnitl; // isLoading = true; //先加载依赖项 yield return(Main.instance.StartCoroutine(LoadDependenciesAssetBundleAsync(resInfo.assetBundleName))); DateTime loadedTime = DateTime.Now; UnityEngine.Object asset = null; if (resourcesMode == ResourcesMode.Resources) { ResourceRequest resourceRequest = Resources.LoadAsync(resInfo.resPath); while (!resourceRequest.isDone) { if (loadingProcess != null) { loadingProcess.Invoke(resourceRequest.progress); yield return(null); } } asset = resourceRequest.asset; } else { if (assetBundles.ContainsKey(resInfo.assetBundleName)) { if (loadingProcess != null) { loadingProcess.Invoke(1); } yield return(null); this.d("LoadAssetAsync", assetBundles[resInfo.assetBundleName] == null); // asset = assetBundles[resInfo.assetBundleName].LoadAsset(resInfo.assetPath); } else { using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(assetBundleRootPath + resInfo.assetBundleName)) { request.SendWebRequest(); while (!request.isDone) { if (loadingProcess != null) { loadingProcess(request.downloadProgress); } yield return(null); } if (!request.isHttpError && !request.isNetworkError) { AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(request); if (assetBundle != null) { asset = assetBundle.LoadAsset <UnityEngine.Object>(resInfo.assetPath); this.d("damon", "----"); } if (isCahce) { if (!assetBundles.ContainsKey(resInfo.assetBundleName)) { assetBundles[resInfo.assetBundleName] = assetBundle; } } else { assetBundle.Unload(false); } } } } } if (loadedSuccess != null) { loadedSuccess(asset); } yield return(null); }
//加载元操作 private IEnumerator LoadAssetPrimitiveAsync(AssetLoadHandler handler) { if (string.IsNullOrEmpty(handler.path)) { LoadAssetPrimitiveCallback(handler, AssetLoadResult.EMPTY_RESULT); yield break; } string assetPath = handler.path; string assetName = null; AssetPathUtil.SpliteBundlePath(handler.path, out assetPath, out assetName); Object asset = null; bool isDone = false; //是否已经在加载池中,如果是就直接返回,引用数加1 var bundleObject = GetBundleObject(assetPath); if (bundleObject != null) { asset = bundleObject.assetBundle; isDone = true; } else { if (AssetPathUtil.IsUrl(assetPath)) //是否为网络路径 { handler.timeoutChecker.stayTime = HANDLER_BUNDLE_NETWORK_STAY_TIME; //网络Handler超时时间 var request = UnityWebRequestAssetBundle.GetAssetBundle(assetPath); request.timeout = (int)handler.timeoutChecker.stayTime; m_handlerWithRequestMap[handler.id] = new RequestObj() { id = handler.id, webRequest = request, }; yield return(request.SendWebRequest()); asset = DownloadHandlerAssetBundle.GetContent(request); isDone = request.isDone; } else { handler.timeoutChecker.stayTime = HANDLER_BUNDLE_LOCAL_STAY_TIME; //本地Handler超时时间 var request = AssetBundle.LoadFromFileAsync(assetPath); m_handlerWithRequestMap[handler.id] = new RequestObj() { id = handler.id, abRequest = request, }; yield return(request); asset = request.assetBundle; isDone = request.isDone; } //先把加载到的AssetBundle加入记录缓存,并且标记引用次数+1 //不记录Bundle为空的项 LoadAssetBundleCallback(handler, asset as AssetBundle); } //////////////////////////////// var assetBundle = asset as AssetBundle; if (assetBundle != null) { if (!string.IsNullOrEmpty(assetName)) { var loadRequest = assetBundle.LoadAssetAsync(assetName); yield return(loadRequest); asset = loadRequest.asset; isDone = loadRequest.isDone; } } var result = new AssetLoadResult(asset, isDone); LoadAssetPrimitiveCallback(handler, result); }
public static void WriteAllDependenciesRes(StreamWriter sw, bool isIndepent = false) { Manifest manifest = new Manifest(); var url = ""; if (isIndepent) { url = AssetBundleUtility.GetIndependentAssetBundleFileUrl(manifest.AssetbundleName); } else { url = AssetBundleUtility.GetAssetBundleFileUrl(manifest.AssetbundleName); } // 说明:同时请求资源可以提高加载速度 UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url); request.SendWebRequest(); while (!request.isDone) { System.Threading.Thread.Sleep(1); } AssetBundle assetbundle = DownloadHandlerAssetBundle.GetContent(request); manifest.LoadFromAssetbundle(assetbundle); var allAssetbundleNames = manifest.GetAllAssetBundleNames(); foreach (var curAssetbundleName in allAssetbundleNames) { if (string.IsNullOrEmpty(curAssetbundleName)) { continue; } int count = 0; foreach (var checkAssetbundle in allAssetbundleNames) { if (checkAssetbundle == curAssetbundleName || string.IsNullOrEmpty(checkAssetbundle)) { continue; } var allDependencies = manifest.GetAllDependencies(checkAssetbundle); if (Array.IndexOf(allDependencies, curAssetbundleName) >= 0) { count++; if (count >= 2) { break; } } } if (count > 0) { sw.WriteLine(curAssetbundleName + "\t" + count); } } assetbundle.Unload(true); request.Dispose(); }
private IEnumerator BuildFirstCache() { var config = _context.GetConfigHolder(); var resVersion = config.ResourceVersion; using (var manifestReq = UnityWebRequest.GetAssetBundle( Path.Combine(StreamingAssetsPath, "StreamingAssets"), (uint)resVersion, (uint)0)) { manifestReq.SendWebRequest(); while (!manifestReq.isDone) { yield return(null); } if (manifestReq.isNetworkError || manifestReq.isHttpError) { MyLog.ErrorWithFrame(name, "加manifest失败 error " + manifestReq.error + " manifestPath = " + Path.Combine(StreamingAssetsPath, "StreamingAssets")); SetBuildFirstCacheResult(BuildFirstCacheResult.Error, string.Format("初始化资源列表失败,请重新登陆\n【错误码{0}】)", NetworkStateErrorCode.BuildFirstCacheFailCode)); yield break; } var manifestBundle = DownloadHandlerAssetBundle.GetContent(manifestReq); if (manifestBundle == null) { MyLog.ErrorWithFrame(name, " manifestBundle == null manifestPath = " + Path.Combine(StreamingAssetsPath, "StreamingAssets")); SetBuildFirstCacheResult(BuildFirstCacheResult.Error, string.Format("获取初始化资源失败,请重新登陆\n【错误码{0}】)", NetworkStateErrorCode.BuildFirstCacheFailCode)); yield break; } var manifest = manifestBundle.LoadAsset <AssetBundleManifest>("AssetBundleManifest"); if (manifest == null) { MyLog.ErrorWithFrame(name, " manifest =null " + Path.Combine(StreamingAssetsPath, "StreamingAssets")); SetBuildFirstCacheResult(BuildFirstCacheResult.Error, string.Format("获取初始化资源失败,请重新登陆\n【错误码{0}】)", NetworkStateErrorCode.BuildFirstCacheFailCode)); yield break; } var allAssetBundles = manifest.GetAllAssetBundles(); if (allAssetBundles == null || allAssetBundles.Length <= 0) { MyLog.ErrorWithFrame(name, "allAssetBundles == null manifest = " + Path.Combine(StreamingAssetsPath, "StreamingAssets")); SetBuildFirstCacheResult(BuildFirstCacheResult.Error, string.Format("获取初始化资源失败,请重新登陆\n【错误码{0}】)", NetworkStateErrorCode.BuildFirstCacheFailCode)); yield break; } var downloadAssetBundleInfo = new DownloadAssetBundleInfo(); downloadAssetBundleInfo.LoadType = DownloadAssetBundleInfo.DownloadType.FirstBuild; downloadAssetBundleInfo.TotalCount = allAssetBundles.Length; downloadAssetBundleInfo.CompleteCount = 0; foreach (var abName in allAssetBundles) { if (string.IsNullOrEmpty(abName)) { continue; } _downloadAssetBundleInfo.Write(downloadAssetBundleInfo, Time.time); using (var bundleReq = UnityWebRequest.GetAssetBundle( Path.Combine(StreamingAssetsPath, abName), (uint)resVersion, (uint)0)) { bundleReq.SendWebRequest(); while (!bundleReq.isDone) { yield return(null); } if (bundleReq.isNetworkError || bundleReq.isHttpError) { MyLog.ErrorWithFrame(name, abName + " upload to cache fail "); SetBuildFirstCacheResult(BuildFirstCacheResult.Error, string.Format( "下载获取初始化资源失败,请重新登陆\n【错误码{0}】)", NetworkStateErrorCode.BuildFirstCacheFailCode)); yield break; } downloadAssetBundleInfo.CompleteCount++; } } yield return(null); _downloadAssetBundleInfo.ClearAndInvalidate(Time.time); MyLog.InfoWithFrame(name, " upload all resource succ >>>>>>>>>>>>> UnloadAllAssetBundles >>>>>>>>>>>"); SetBuildFirstCacheResult(BuildFirstCacheResult.Ok, ""); AssetBundle.UnloadAllAssetBundles(false); } }
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); } }; } }
/// <summary> /// load assetbundle manifest, check hash, load actual bundle with hash parameter to use caching /// instantiate gameobject /// </summary> /// <param name="bundleURL">full url to assetbundle file</param> /// <param name="assetName">optional parameter to access specific asset from assetbundle</param> /// <returns></returns> /// IEnumerator DownloadAndCache(string bundleURL, string assetName = "") IEnumerator DownloadAndCache(string bundleURL) { // Wait for the Caching system to be ready while (!Caching.ready) { yield return(null); } // if you want to always load from server, can clear cache first // Caching.CleanCache(); // get current bundle hash from server, random value added to avoid caching UnityWebRequest uwrABManifest = UnityWebRequest.Get(bundleURL + ".manifest?r=" + RandomHash(32)); //UnityWebRequest uwr = UnityWebRequest.Get(bundleURL + ".manifest"); Debug.Log("Loading manifest:" + bundleURL + ".manifest"); // wait for load to finish yield return(uwrABManifest.SendWebRequest()); // if received error, exit if (uwrABManifest.isNetworkError) { Debug.LogError("www error: " + uwrABManifest.error); uwrABManifest.Dispose(); uwrABManifest = null; yield break; } // create empty hash string Hash128 hashString = (default(Hash128));// new Hash128(0, 0, 0, 0); // check if received data contains 'ManifestFileVersion' Debug.Log("manifest file " + uwrABManifest.downloadHandler.text); if (uwrABManifest.downloadHandler.text.Contains("ManifestFileVersion")) { // extract hash string from the received data, TODO should add some error checking here var hashRow = uwrABManifest.downloadHandler.text.ToString().Split("\n".ToCharArray())[5]; hashString = Hash128.Parse(hashRow.Split(':')[1].Trim()); if (hashString.isValid == true) { // we can check if there is cached version or not if (Caching.IsVersionCached(bundleURL, hashString) == true) { Debug.Log("Bundle with this hash is already cached!"); isCached = true; } else { Debug.Log("No cached version found for this hash.."); isCached = false; } } else { // invalid loaded hash, just try loading latest bundle Debug.LogError("Invalid hash:" + hashString); yield break; } } else { Debug.LogError("Manifest doesn't contain string 'ManifestFileVersion': " + bundleURL + ".manifest"); yield break; } // now download the actual bundle, with hashString parameter it uses cached version if available uwrAssetBundle = UnityWebRequestAssetBundle.GetAssetBundle(bundleURL + "?r=" + RandomHash(32), hashString, 0); Debug.Log("I am initiating a Unity Web Request for the Asset Bundle NOW."); // wait for load to finish isLoading = true; yield return(uwrAssetBundle.SendWebRequest()); Debug.Log("Unity has returned from the UWR."); if (uwrAssetBundle.error != null || uwrAssetBundle.isNetworkError) { Debug.LogError("www error: " + uwrAssetBundle.error); uwrAssetBundle.Dispose(); uwrAssetBundle = null; yield break; } // get bundle from downloadhandler //AssetBundle bundle = ((DownloadHandlerAssetBundle)uwr.downloadHandler).assetBundle; Debug.Log("The UWR came back fine and now I am initiating the actual download of the Asset Bundle."); AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwrAssetBundle); //isLoading = true; if (uwrAssetBundle.isDone) { isLoading = false; //AssetBundleManifest manifest = bundle.LoadAsset<AssetBundleManifest>(bundle.name); Debug.Log("The Asset Bundle has been downloaded successfully."); 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]); } //// fix pink shaders, NOTE: not always needed.. //foreach (Renderer r in go.GetComponentsInChildren<Renderer>(includeInactive: true)) //{ // // FIXME: creates multiple materials, not good // var material = Shader.Find(r.material.shader.name); // r.material.shader = null; // r.material.shader = material; //} SceneManager.LoadSceneAsync(bundle.GetAllScenePaths()[0]); } /* * //GameObject bundlePrefab = null; * * // if no asset name is given, take the first/main asset * if (assetName == "") * { * bundlePrefab = (GameObject)bundle.LoadAsset(bundle.GetAllAssetNames()[0]); * } * else * { // use asset name to access inside bundle * bundlePrefab = (GameObject)bundle.LoadAsset(assetName); * } * * // if we got something out * if (bundlePrefab != null) * { * * // instantiate at 0,0,0 and without rotation * Instantiate(bundlePrefab, Vector3.zero, Quaternion.identity); * * * //// fix pink shaders, NOTE: not always needed.. * //foreach (Renderer r in go.GetComponentsInChildren<Renderer>(includeInactive: true)) * //{ * // // FIXME: creates multiple materials, not good * // var material = Shader.Find(r.material.shader.name); * // r.material.shader = null; * // r.material.shader = material; * //} * } */ uwrAssetBundle.Dispose(); uwrAssetBundle = null; // try to cleanup memory Resources.UnloadUnusedAssets(); bundle.Unload(false); bundle = null; }
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(); } }; } }
static IEnumerator CoInitalizeLocalBundles(BundleAsyncOperation result, bool autoReloadBundle) { if (Initialized) { result.Done(BundleErrorCode.Success); yield break; } AutoReloadBundle = autoReloadBundle; if (UseAssetDatabase) { Initialized = true; result.Done(BundleErrorCode.Success); yield break; } if (LogMessages) { Debug.Log($"LocalURL : {LocalURL}"); } foreach (var kv in s_AssetBundles) { kv.Value.Bundle.Unload(false); } s_SceneNames.Clear(); s_AssetBundles.Clear(); s_LocalBundles.Clear(); var manifestReq = UnityWebRequest.Get(Path.Combine(LocalURL, AssetbundleBuildSettings.ManifestFileName)); yield return(manifestReq.SendWebRequest()); if (manifestReq.isHttpError || manifestReq.isNetworkError) { result.Done(BundleErrorCode.NetworkError); yield break; } if (!AssetbundleBuildManifest.TryParse(manifestReq.downloadHandler.text, out var localManifest)) { result.Done(BundleErrorCode.ManifestParseError); yield break; } //cached version is recent one. var path = Path.Combine(Application.persistentDataPath, CACHED_MANIFEST_FILE_NAME); var cachedManifestJson = string.Empty; if (File.Exists(path)) { cachedManifestJson = File.ReadAllText(path); } var cacheIsValid = AssetbundleBuildManifest.TryParse(PlayerPrefs.GetString(cachedManifestJson, string.Empty), out var cachedManifest) && cachedManifest.BuildTime > localManifest.BuildTime; result.SetIndexLength(localManifest.BundleInfos.Count); for (int i = 0; i < localManifest.BundleInfos.Count; i++) { result.SetCurrentIndex(i); result.SetCachedBundle(true); AssetbundleBuildManifest.BundleInfo bundleInfoToLoad; AssetbundleBuildManifest.BundleInfo cachedBundleInfo = default; var localBundleInfo = localManifest.BundleInfos[i]; bool useLocalBundle = !cacheIsValid || //cache is not valid or... !cachedManifest.TryGetBundleInfo(localBundleInfo.BundleName, out cachedBundleInfo) || //missing bundle or... !Caching.IsVersionCached(cachedBundleInfo.AsCached); //is not cached no unusable. bundleInfoToLoad = useLocalBundle ? localBundleInfo : cachedBundleInfo; var loadPath = Path.Combine(LocalURL, bundleInfoToLoad.BundleName); var bundleReq = UnityWebRequestAssetBundle.GetAssetBundle(loadPath, bundleInfoToLoad.Hash); var bundleOp = bundleReq.SendWebRequest(); while (!bundleOp.isDone) { result.SetProgress(bundleOp.progress); yield return(null); } if (!bundleReq.isHttpError && !bundleReq.isNetworkError) { var loadedBundle = new LoadedBundle(bundleInfoToLoad, loadPath, DownloadHandlerAssetBundle.GetContent(bundleReq), useLocalBundle); s_AssetBundles.Add(localBundleInfo.BundleName, loadedBundle); CollectSceneNames(loadedBundle); if (LogMessages) { Debug.Log($"Local bundle Loaded - Name : {localBundleInfo.BundleName}, Hash : {bundleInfoToLoad.Hash }"); } } else { result.Done(BundleErrorCode.NetworkError); yield break; } bundleReq.Dispose(); s_LocalBundles.Add(localBundleInfo.BundleName, localBundleInfo.Hash); } RemoteURL = Path.Combine(localManifest.RemoteURL, localManifest.BuildTarget); #if UNITY_EDITOR if (s_EditorBuildSettings.EmulateWithoutRemoteURL) { RemoteURL = "file://" + Path.Combine(s_EditorBuildSettings.RemoteOutputPath, UnityEditor.EditorUserBuildSettings.activeBuildTarget.ToString()); } #endif Initialized = true; if (LogMessages) { Debug.Log($"Initialize Success \nRemote URL : {RemoteURL} \nLocal URL : {LocalURL}"); } result.Done(BundleErrorCode.Success); }
private IEnumerator LoadScreen(string screenId, string screenPath) { GameObject newScreen; PreviousScreenID = currentScreen.screenId; // when running on webgl; only load game screen from resource if ((Application.platform != RuntimePlatform.WebGLPlayer && PersistentModel.Instance.RunLocation != PersistentModel.RUN_LOCATION.Client) || screenId == GAME_SCREEN) { ResourceRequest resourceRequest = Resources.LoadAsync <BaseScreen>(screenPath); while (!resourceRequest.isDone) { yield return(null); } transitioningScreenId = screenId; transitioningScreen = Instantiate <BaseScreen>(resourceRequest.asset as BaseScreen, transform); transitioningScreen.transform.SetAsFirstSibling(); transitioningScreen.Initialize(screenId); // loading is complete if (ProgressLoadingPanel) { ProgressLoadingPanel.GetComponent <ProgressLoadingPanel>().LoadingPercent.text = "100%"; } } else { string url = PersistentModel.Instance.AssetBundlesURL + screenId.ToLower(); UnityWebRequest request = new UnityWebRequest(url) { downloadHandler = new DownloadHandlerAssetBundle(url, 1, 0), certificateHandler = new SSLAuth() }; request.SendWebRequest(); while (!request.isDone) { ProgressLoadingPanel.GetComponent <ProgressLoadingPanel>().LoadingPercent.text = Mathf.CeilToInt(request.downloadProgress * 100).ToString() + "%"; yield return(waitSecAssetLoad); } AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request); AssetBundleRequest bundleRequest = bundle.LoadAssetAsync(screenId); yield return(bundleRequest); newScreen = Instantiate <GameObject>(bundleRequest.asset as GameObject); bundle.Unload(false); ProgressLoadingPanel.GetComponent <ProgressLoadingPanel>().LoadingPercent.text = "100%"; // Wait for the load yield return(newScreen); // add Parent, and Add it in the 1st index of Parent // so that we can have the new screen behind the current screen newScreen.transform.SetParent(transform, false); newScreen.transform.SetAsFirstSibling(); newScreen.GetComponent <BaseScreen>().Initialize(screenId); // add to list transitioningScreenId = screenId; transitioningScreen = newScreen.GetComponent <BaseScreen>(); } // isLoadingRequiredBeforeDraw is when loading the game screen and track if (!transitioningScreen.isLoadingRequiredBeforeDraw) { if (currentScreen != null) { Color activeColor = currentScreen.gameObject.GetComponent <Image>().color; activeColor.a = 1f; // fadeout background image color from screen LeanTween.value(1f, 0f, 0.75f) .setDelay(0.25f) .setEase(LeanTweenType.easeOutQuad) .setOnUpdate((float val) => { activeColor.a = val; currentScreen.gameObject.GetComponent <Image>().color = activeColor; }) .setOnComplete(() => { // ignore closing sequence, start transition in right away after race. if (screenId == CONGRATULATIONS_SCREEN) { ShowTransitionedScreen(); } else { // scales and fades in side panels // transitioningScreen.ScaleInPanels(); LeanTween.delayedCall(0.5f, transitioningScreen.ScaleInPanels); // add event when loading close sequence is complete currentScreen.OnCloseLoadingPanelComplete += CurrentScreen_OnCloseLoadingPanelComplete; // start Close Panel sequence currentScreen.CloseLoadingPanel(); } }); } else { Color activeColor = transitioningScreen.gameObject.GetComponent <Image>().color; activeColor.a = 1f; // fadeout background image color from screen LeanTween.value(1f, 0f, 0.15f) .setDelay(0.0f) .setEase(LeanTweenType.easeOutQuad) .setOnUpdate((float val) => { activeColor.a = val; transitioningScreen.gameObject.GetComponent <Image>().color = activeColor; }) .setOnComplete(() => { // scales and fades in side panels transitioningScreen.ScaleInPanels(); LeanTween.delayedCall(0.65f, ShowTransitionedScreen); }); // ShowTransitionedScreen(); yield return(0); } } else { ShowTransitionedScreen(); } }
static IEnumerator CoDownloadAssetBundles(AssetbundleBuildManifest manifest, IEnumerable <string> subsetNames, BundleAsyncOperation <bool> result) { if (!Initialized) { Debug.LogError("Do Initialize first"); result.Done(BundleErrorCode.NotInitialized); yield break; } if (UseAssetDatabase) { result.Done(BundleErrorCode.Success); yield break; } var bundlesToUnload = new HashSet <string>(s_AssetBundles.Keys); var downloadBundleList = subsetNames == null ? manifest.BundleInfos : manifest.CollectSubsetBundleInfoes(subsetNames); var bundleReplaced = false; //bundle has been replaced result.SetIndexLength(downloadBundleList.Count); for (int i = 0; i < downloadBundleList.Count; i++) { result.SetCurrentIndex(i); var bundleInfo = downloadBundleList[i]; //remove from the set so we can track bundles that should be cleared bundlesToUnload.Remove(bundleInfo.BundleName); var islocalBundle = s_LocalBundles.TryGetValue(bundleInfo.BundleName, out var localHash) && localHash == bundleInfo.Hash; var isCached = Caching.IsVersionCached(bundleInfo.AsCached); result.SetCachedBundle(isCached); var loadURL = islocalBundle ? Path.Combine(LocalURL, bundleInfo.BundleName) : Path.Combine(RemoteURL, bundleInfo.BundleName); if (LogMessages) { Debug.Log($"Loading Bundle Name : {bundleInfo.BundleName}, loadURL {loadURL}, isLocalBundle : {islocalBundle}, isCached {isCached}"); } LoadedBundle previousBundle; if (s_AssetBundles.TryGetValue(bundleInfo.BundleName, out previousBundle) && previousBundle.Hash == bundleInfo.Hash) { if (LogMessages) { Debug.Log($"Loading Bundle Name : {bundleInfo.BundleName} Complete - load skipped"); } } else { var bundleReq = islocalBundle ? UnityWebRequestAssetBundle.GetAssetBundle(loadURL) : UnityWebRequestAssetBundle.GetAssetBundle(loadURL, bundleInfo.AsCached); var operation = bundleReq.SendWebRequest(); while (!bundleReq.isDone) { result.SetProgress(operation.progress); yield return(null); } if (bundleReq.isNetworkError || bundleReq.isHttpError) { result.Done(BundleErrorCode.NetworkError); yield break; } if (s_AssetBundles.TryGetValue(bundleInfo.BundleName, out previousBundle)) { bundleReplaced = true; previousBundle.Bundle.Unload(false); if (previousBundle.RequestForReload != null) { previousBundle.RequestForReload.Dispose(); //dispose reload bundle } s_AssetBundles.Remove(bundleInfo.BundleName); } var loadedBundle = new LoadedBundle(bundleInfo, loadURL, DownloadHandlerAssetBundle.GetContent(bundleReq), islocalBundle); s_AssetBundles.Add(bundleInfo.BundleName, loadedBundle); CollectSceneNames(loadedBundle); if (LogMessages) { Debug.Log($"Loading Bundle Name : {bundleInfo.BundleName} Complete"); } bundleReq.Dispose(); } } //let's drop unknown bundles loaded foreach (var name in bundlesToUnload) { var bundleInfo = s_AssetBundles[name]; bundleInfo.Bundle.Unload(false); if (bundleInfo.RequestForReload != null) { bundleInfo.RequestForReload.Dispose(); //dispose reload bundle } s_AssetBundles.Remove(bundleInfo.Name); } //bump entire bundles' usage timestamp //we use manifest directly to find out entire list for (int i = 0; i < manifest.BundleInfos.Count; i++) { var cachedInfo = manifest.BundleInfos[i].AsCached; if (Caching.IsVersionCached(cachedInfo)) { Caching.MarkAsUsed(cachedInfo); } } if (LogMessages) { Debug.Log($"CacheUsed Before Cleanup : {Caching.defaultCache.spaceOccupied} bytes"); } Caching.ClearCache(600); //as we bumped entire list right before clear, let it be just 600 if (LogMessages) { Debug.Log($"CacheUsed After CleanUp : {Caching.defaultCache.spaceOccupied} bytes"); } // PlayerPrefs to PersistentDataPath File.WriteAllText(Path.Combine(Application.persistentDataPath, CACHED_MANIFEST_FILE_NAME), JsonUtility.ToJson(manifest)); GlobalBundleHash = manifest.GlobalHash.ToString(); result.Result = bundleReplaced; result.Done(BundleErrorCode.Success); }
/// <summary> /// Create the dash and present it /// </summary> /// <returns></returns> private IEnumerator _presentYURGUI(bool UsingYURinteractionSystem) { Vector3 YUR_Position; Vector3 YUR_Direction; /// Display the ScreenCoordinator Object and set the background color of the Dash YURScreenCoordinator.ScreenCoordinator.gameObject.SetActive(true); YURScreenCoordinator.ScreenCoordinator.Background.GetComponent <UnityEngine.UI.Image>().color = YUR.Yur.BackgroundColor; GameObject Camera = YUR.Yur.Camera; /// If a previously specified gameobject is to be used for the location of dash. if (YUR.Yur.GUITransform != null) { Debug.Log("Displaying on GUITransform", YUR.Yur.GUITransform); YUR.Yur.YUR_Dash.transform.localScale = new Vector3(YUR.Yur.YUR_Dash.transform.localScale.x * (YUR.Yur.YURGUIScale + 1), YUR.Yur.YUR_Dash.transform.localScale.y * (YUR.Yur.YURGUIScale + 1), YUR.Yur.YUR_Dash.transform.localScale.z * (YUR.Yur.YURGUIScale + 1)); YUR.Yur.YUR_Dash.transform.SetParent(YUR.Yur.GUITransform.transform); YUR.Yur.YUR_Dash.transform.localPosition = YUR.Yur.YURGUIPositionOffset; YUR.Yur.YUR_Dash.transform.localEulerAngles = YUR.Yur.YURGUIRotationOffset; } else /// Else, position the dash relative to the camera position; { YUR_Log.Log("Moving Dash in front of player"); YUR_Position = Camera.transform.position; YUR_Direction = Camera.transform.forward; YUR_Direction.y = 0; YUR_Log.Log("Dash Positioning: \nPosition: " + YUR_Position + "\nDirection: " + YUR_Direction + "\nYUR Dash Position: " + YUR.Yur.YUR_Dash.transform.position, YUR.Yur.YUR_Dash); YUR.Yur.YUR_Dash.transform.SetPositionAndRotation( new Vector3(YUR_Position.x + (YUR_Direction.x * 2), YUR_Position.y, YUR_Position.z + (YUR_Direction.z * 2)), Quaternion.LookRotation(YUR_Direction)); YUR_Log.Log("Dash Positioning: \nPosition: " + YUR_Position + "\nDirection: " + YUR_Direction + "\nYUR Dash Position: " + YUR.Yur.YUR_Dash.transform.position, YUR.Yur.YUR_Dash); } /// Present the first screen to user YURScreenCoordinator.ScreenCoordinator.Hierarchy[0].gameObject.SetActive(true); bool leftHanded = false; bool instantiatedUIKit = false; int children; /// Deteremine the number of children in which the Camera object has, differing counts are for different platforms if (Camera.transform.parent) { children = Camera.transform.parent.childCount; } else { children = Camera.transform.childCount; } if (!UsingYURinteractionSystem) // If Not using YUR Interaction System, stop here { yield break; } if (YUR.Yur.YURAssetBundle == null) { string URI = "file:///" + Application.dataPath + "/AssetBundles/" + YUR.Yur.assetBundleName; UnityEngine.Networking.UnityWebRequest request = UnityEngine.Networking.UnityWebRequestAssetBundle.GetAssetBundle(URI, 0); yield return(request.SendWebRequest()); if (request.error != null) { yield break; } else { YUR_Log.Log("Local asset bundle found!"); yield return(YUR.Yur.YURAssetBundle = DownloadHandlerAssetBundle.GetContent(request)); } } ////_____________________________________________________________________________________/ /// Take Control of the Event System, is returned when YUR Dash is closed. //_____________________________________________________________________________________/ OriginalEventSystem = UnityEngine.EventSystems.EventSystem.current; if (YUR.Yur.platform == VRUiKits.Utils.VRPlatform.OCULUS) { GameObject temppp; yield return(temppp = YUR.Yur.YURAssetBundle.LoadAsset <GameObject>("LaserInputModuleOculus")); YUR_Log.Log("Loaded the Laser Input Module for Oculus, instantiating"); yield return(EventSystem = (Instantiate(temppp) as GameObject));// = EventSystem.gameObject.AddComponent<VRUiKits.Utils.OculusLaserInputModule>(); EventSystem.name = "Event System"; UnityEngine.EventSystems.EventSystem.current = EventSystem.GetComponent <UnityEngine.EventSystems.EventSystem>(); YUR.Yur.eventSystem = EventSystem.GetComponent <UnityEngine.EventSystems.EventSystem>(); yield return(LaserIM = EventSystem.GetComponent <VRUiKits.Utils.LaserInputModule>()); YUR_Log.Log("Oculus Input Module Added"); } else if (YUR.Yur.platform == VRUiKits.Utils.VRPlatform.VIVE_STEAM2) { var temppp = YUR.Yur.YURAssetBundle.LoadAsset <GameObject>("LaserInputModuleSteam2"); yield return(EventSystem = (Instantiate(temppp) as GameObject));// = EventSystem.gameObject.AddComponent<VRUiKits.Utils.OculusLaserInputModule>(); EventSystem.name = "Event System"; UnityEngine.EventSystems.EventSystem.current = EventSystem.GetComponent <UnityEngine.EventSystems.EventSystem>(); YUR.Yur.eventSystem = EventSystem.GetComponent <UnityEngine.EventSystems.EventSystem>(); yield return(LaserIM = EventSystem.GetComponent <VRUiKits.Utils.LaserInputModule>()); YUR_Log.Log("Steam Input Module Added"); } if (YUR.Yur.platform == VRUiKits.Utils.VRPlatform.OCULUS) /// If the platform is defined as being Oculus, use the Camera object to locate the Controllers { YUR_Log.Log("Locating Oculus Controllers..."); for (int i = 0; i < YUR.Yur.Camera.transform.parent.childCount; i++) { if (YUR.Yur.Camera.transform.parent.GetChild(i).gameObject.name.Contains("RightHand")) { var temppp = YUR.Yur.YURAssetBundle.LoadAsset <GameObject>("OculusUIKitPointer"); UIPointerKit = Instantiate(temppp, YUR.Yur.Camera.transform.parent.GetChild(i).gameObject.transform); //UIPointerKit = (GameObject)Instantiate(Resources.Load("OculusUIKitPointer"), YUR.Yur.Camera.transform.parent.GetChild(i).gameObject.transform); instantiatedUIKit = true; leftHanded = false; YUR_Log.Log("Found Oculus Controller Right"); break; } else if (YUR.Yur.Camera.transform.parent.GetChild(i).gameObject.name.Contains("LeftHand")) { var temppp = YUR.Yur.YURAssetBundle.LoadAsset <GameObject>("OculusUIKitPointer"); UIPointerKit = Instantiate(temppp, YUR.Yur.Camera.transform.parent.GetChild(i).gameObject.transform); //UIPointerKit = (GameObject)Instantiate(Resources.Load("OculusUIKitPointer"), YUR.Yur.Camera.transform.parent.GetChild(i).gameObject.transform); instantiatedUIKit = true; leftHanded = true; YUR_Log.Log("Found Oculus Controller Left"); break; } } } else if (YUR.Yur.platform == VRUiKits.Utils.VRPlatform.VIVE_STEAM2) /// If the platform is Steam VR 2, find the preferred controller. { YUR_Log.Log("Locating Steam VR 2 Controllers..."); for (int i = 0; i < children; i++) { Debug.Log("Found Controller: " + Camera.transform.parent.GetChild(i).gameObject.name); if (Camera.transform.parent.GetChild(i).gameObject.name.Contains("right")) { var temppp = YUR.Yur.YURAssetBundle.LoadAsset <GameObject>("Steam2UIKitPointer"); UIPointerKit = Instantiate(temppp, YUR.Yur.Camera.transform.parent.GetChild(i).gameObject.transform); // UIPointerKit = (GameObject)Instantiate(Resources.Load("Steam2UIKitPointer"), Camera.transform.parent.GetChild(i).gameObject.transform); instantiatedUIKit = true; leftHanded = false; YUR_Log.Log("Found Steam Controller right"); break; } if (Camera.transform.parent.GetChild(i).gameObject.name.Contains("left")) { var temppp = YUR.Yur.YURAssetBundle.LoadAsset <GameObject>("Steam2UIKitPointer"); UIPointerKit = Instantiate(temppp, YUR.Yur.Camera.transform.parent.GetChild(i).gameObject.transform); // UIPointerKit = (GameObject)Instantiate(Resources.Load("Steam2UIKitPointer"), Camera.transform.parent.GetChild(i).gameObject.transform); instantiatedUIKit = true; leftHanded = true; YUR_Log.Log("Found Steam Controller Left"); break; } } } LaserIM.platform = YUR.Yur.platform; LaserIM.pointer = (leftHanded ? VRUiKits.Utils.Pointer.LeftHand : VRUiKits.Utils.Pointer.RightHand); if (!instantiatedUIKit) // If UIPointerKit not previously instantiated { var temppp = YUR.Yur.YURAssetBundle.LoadAsset <GameObject>("UIKitPointer"); UIPointerKit = Instantiate(temppp); //UIPointerKit = (GameObject)Instantiate(Resources.Load("UIKitPointer")); } //YUR_Log.Log("Checking for event system..."); //if (YUR.Yur.eventSystem == null) // If there is no event system, create a new gameobject and attach an Event System Component //{ // YUR_Log.Log("None found, create event system..."); // //EventSystem = new GameObject("EventSystem"); // //yield return YUR.Yur.eventSystem = EventSystem.AddComponent<UnityEngine.EventSystems.EventSystem>(); //} //else //{ // YUR_Log.Log("Found event System"); // EventSystem = YUR.Yur.eventSystem.gameObject; //} //if(EventSystem.gameObject.GetComponent<VRUiKits.Utils.VREventSystemHelper>()) //{ // YUR_Log.Log("VR Event System Helper already added to game object"); //} //else //{ // YUR_Log.Log("Adding Event System Helper and Input Module"); // EventSystem.gameObject.AddComponent<VRUiKits.Utils.VREventSystemHelper>(); //} }
/// <summary> /// 读取字节 /// 1.File.ReadAllBytes(path) /// 2.WWW /// </summary> /// <param name="path">路径</param> /// <param name="streamMethod">形式</param> /// <param name="cotiner">字节容器</param> /// <returns></returns> private IEnumerator ExecuteLoadBundleAsync(string path, BundleLoadMethod streamMethod, BundleContainer container) { // Debug.Log(streamMethod); switch (streamMethod) { case BundleLoadMethod.WWW_LoadBundleAndBytes: { var webBbLoadRequest = UnityWebRequest.Get(path); yield return(webBbLoadRequest.SendWebRequest()); container.bytes = webBbLoadRequest.downloadHandler.data; var bundleCreationRequest = AssetBundle.LoadFromMemoryAsync(container.bytes); yield return(bundleCreationRequest); container.assetBundle = bundleCreationRequest.assetBundle; break; } case BundleLoadMethod.WWW_LoadBytes: { var webBytesLoadRequest = UnityWebRequest.Get(path); yield return(webBytesLoadRequest.SendWebRequest()); container.bytes = webBytesLoadRequest.downloadHandler.data; break; } case BundleLoadMethod.WWW_LoadBundle: { var webBundleRequest = UnityWebRequestAssetBundle.GetAssetBundle(path); yield return(webBundleRequest.SendWebRequest()); container.assetBundle = DownloadHandlerAssetBundle.GetContent(webBundleRequest); break; } case BundleLoadMethod.File_LocalBundle: { var fileBundleRequest = AssetBundle.LoadFromFileAsync(path); yield return(fileBundleRequest); container.assetBundle = fileBundleRequest.assetBundle; break; } case BundleLoadMethod.File_StreamingBundle: { var fileBundleRequest = AssetBundle.LoadFromFileAsync(path); yield return(fileBundleRequest); container.assetBundle = fileBundleRequest.assetBundle; break; } case BundleLoadMethod.File_Bytes: break; default: yield break; } }
/// <summary> /// 轮询更新 /// </summary> public override void Update() { if (_steps == ESteps.Done) { return; } if (_steps == ESteps.None) { if (MainBundleInfo.IsInvalid) { _steps = ESteps.Done; Status = EStatus.Failed; LastError = $"The bundle info is invalid : {MainBundleInfo.BundleName}"; YooLogger.Error(LastError); return; } if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming) { _steps = ESteps.LoadFile; _webURL = MainBundleInfo.GetStreamingLoadPath(); } else { throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString()); } } // 1. 从服务器或缓存中获取AssetBundle文件 if (_steps == ESteps.LoadFile) { string hash = StringUtility.RemoveExtension(MainBundleInfo.Hash); _webRequest = UnityWebRequestAssetBundle.GetAssetBundle(_webURL, Hash128.Parse(hash)); _webRequest.SendWebRequest(); _steps = ESteps.CheckFile; } // 2. 检测获取的AssetBundle文件 if (_steps == ESteps.CheckFile) { if (_webRequest.isDone == false) { return; } #if UNITY_2020_1_OR_NEWER if (_webRequest.result != UnityWebRequest.Result.Success) #else if (_webRequest.isNetworkError || _webRequest.isHttpError) #endif { YooLogger.Warning($"Failed to get asset bundle form web : {_webURL} Error : {_webRequest.error}"); _steps = ESteps.TryLoad; _tryTimer = 0; } else { CacheBundle = DownloadHandlerAssetBundle.GetContent(_webRequest); if (CacheBundle == null) { _steps = ESteps.Done; Status = EStatus.Failed; LastError = $"AssetBundle file is invalid : {MainBundleInfo.BundleName}"; YooLogger.Error(LastError); } else { _steps = ESteps.Done; Status = EStatus.Succeed; } } } // 3. 如果获取失败,重新尝试 if (_steps == ESteps.TryLoad) { _tryTimer += Time.unscaledDeltaTime; if (_tryTimer > 1f) { _webRequest.Dispose(); _webRequest = null; _steps = ESteps.LoadFile; } } }
IEnumerator Start() { Debug.Log(Caching.spaceOccupied); // Prevent Test instance destroied when level loading DontDestroyOnLoad(gameObject); // Test start download string[] sceneList = new string[] { "LA", "LB", "LC", "LD" }; foreach (string sceneBundleName in sceneList) { DownloadManager.Instance.StartDownload(sceneBundleName + ".assetBundle"); } if (!DownloadManager.Instance.IsUrlRequested("LA.assetBundle")) { Debug.LogError("TEST:IsUrlRequested() ERORR"); } else { Debug.Log("TEST:IsUrlRequested() test finished."); } bool sceneBundleSucceed = false; do { sceneBundleSucceed = true; foreach (string sceneBundleName in sceneList) { if (DownloadManager.Instance.GetWWW(sceneBundleName + ".assetBundle") == null) { sceneBundleSucceed = false; } } List <string> sceneBundles = new List <string>(); foreach (string sceneBundleName in sceneList) { sceneBundles.Add(sceneBundleName + ".assetBundle"); } float progressOfScenes = DownloadManager.Instance.ProgressOfBundles(sceneBundles.ToArray()); Debug.Log("scenes' Progress {0}", progressOfScenes); yield return(null); }while(!sceneBundleSucceed); Debug.Log("TEST:StartDownload() test finished."); // Test WaitDownload yield return(StartCoroutine(DownloadManager.Instance.WaitDownload("LE.assetBundle"))); Debug.Log("TEST:WaitDownload() test finished."); string errMsg = DownloadManager.Instance.GetError("LE.assetBundle"); if (errMsg == null) { Debug.LogError("TEST:GetError() ERORR"); } else { Debug.Log("TEST:GetError() test finished."); } // Test DisposeWWW() foreach (string sceneBundleName in sceneList) { DownloadManager.Instance.DisposeWWW(sceneBundleName + ".assetBundle"); } if (DownloadManager.Instance.GetWWW("LA.assetBundle") != null) { Debug.LogError("TEST:DisposeWWW() ERORR"); } else { Debug.Log("TEST:DisposeWWW() test finished."); } // Test StopAll() foreach (string sceneBundleName in sceneList) { DownloadManager.Instance.StartDownload(sceneBundleName + ".assetBundle"); } DownloadManager.Instance.StopAll(); yield return(new WaitForSeconds(2f)); if (DownloadManager.Instance.GetWWW("LA.assetBundle") != null) { Debug.LogError("TEST:StopAll() ERORR"); } else { Debug.Log("TEST:StopAll() test finished."); } // Test scene bundles based on scene bundles yield return(StartCoroutine(DownloadManager.Instance.WaitDownload("sub/LA-A.assetBundle"))); #pragma warning disable 0168 var sceneBundle = DownloadHandlerAssetBundle.GetContent(DownloadManager.Instance.GetWWW("sub/LA-A.assetBundle")); #pragma warning restore 0168 #pragma warning disable 0618 Application.LoadLevel("LA-A"); #pragma warning restore 0618 yield return(null); if (GameObject.Find("LA-AWorker") == null) { Debug.LogError("TEST:Load scene bundle based on scene bundle ERORR "); } else { Debug.Log("TEST Load scene bundle based on scene bundle finished."); } // Test asset bundles based on scene bundles yield return(StartCoroutine(DownloadManager.Instance.WaitDownload("AB-A.assetBundle"))); #if UNITY_5 || UNITY_2018 var workerObj = DownloadHandlerAssetBundle.GetContent(DownloadManager.Instance.GetWWW("AB-A.assetBundle")).LoadAsset <GameObject>("worker"); #else var workerObj = DownloadManager.Instance.GetWWW("AB-A.assetBundle").assetBundle.Load("worker"); #endif if (workerObj == null) { Debug.LogError("TEST:Load asset bundle based on scene bundle ERORR"); } else { Debug.Log("TEST Load asset bundle based on scene bundle finished."); } // Test scene bundles based on asset bundles yield return(StartCoroutine(DownloadManager.Instance.WaitDownload("LB-A.assetBundle"))); #pragma warning disable 0168 sceneBundle = DownloadHandlerAssetBundle.GetContent(DownloadManager.Instance.GetWWW("LB-A.assetBundle")); #pragma warning restore 0168 #pragma warning disable 0618 Application.LoadLevel("LB-A"); #pragma warning restore 0618 yield return(null); if (GameObject.Find("LB-AWorker") == null) { Debug.LogError("TEST:Load scene bundle based on asset bundle ERORR "); } else { Debug.Log("TEST Load scene bundle based on asset bundle finished."); } // Test asset bundles based on asset bundles yield return(StartCoroutine(DownloadManager.Instance.WaitDownload("AA-A.assetBundle"))); #if UNITY_5 || UNITY_2018 workerObj = DownloadHandlerAssetBundle.GetContent(DownloadManager.Instance.GetWWW("AA-A.assetBundle")).LoadAsset <GameObject>("worker"); #else workerObj = DownloadManager.Instance.GetWWW("AA-A.assetBundle").assetBundle.Load("worker"); #endif if (workerObj == null) { Debug.LogError("TEST:Load asset bundle based on asset bundle ERORR"); } else { Debug.Log("TEST Load asset bundle based on asset bundle finished."); } // Test Load deep dependend tree yield return(StartCoroutine(DownloadManager.Instance.WaitDownload("LAAAAA.assetBundle"))); #pragma warning disable 0168 sceneBundle = DownloadHandlerAssetBundle.GetContent(DownloadManager.Instance.GetWWW("LAAAAA.assetBundle")); #pragma warning restore 0168 #pragma warning disable 0618 Application.LoadLevel("LAAAAA"); #pragma warning restore 0618 yield return(null); if (GameObject.Find("LAAAAAWorker") == null) { Debug.LogError("TEST:Load deep dependend tree ERORR "); } else { Debug.Log("TEST Load deep dependend tree finished."); } // Test two bundle based on one bundle yield return(StartCoroutine(DownloadManager.Instance.WaitDownload("ACA.assetBundle"))); yield return(StartCoroutine(DownloadManager.Instance.WaitDownload("ACB.assetBundle"))); #if UNITY_5 || UNITY_2018 var cube = DownloadHandlerAssetBundle.GetContent(DownloadManager.Instance.GetWWW("ACA.assetBundle")).LoadAsset <UnityEngine.Object>("Cube"); var sphere = DownloadHandlerAssetBundle.GetContent(DownloadManager.Instance.GetWWW("ACB.assetBundle")).LoadAsset <UnityEngine.Object>("Sphere"); #else var cube = DownloadManager.Instance.GetWWW("ACA.assetBundle").assetBundle.Load("Cube"); var sphere = DownloadManager.Instance.GetWWW("ACB.assetBundle").assetBundle.Load("Sphere"); #endif if (cube == null || sphere == null) { Debug.LogError("TEST: two bundle based on one bundle ERORR"); } else { Debug.Log("TEST two bundle based on one bundle finished"); } // Test Built Bundles if (DownloadManager.Instance.ConfigLoaded) { var bundles = DownloadManager.Instance.BuiltBundles; if (bundles != null && bundles.Length > 0) { Debug.Log("TEST BuiltBundles finished"); } else { Debug.LogError("TEST: BuiltBundles ERORR"); } } Debug.Log("TEST finished"); }
IEnumerator LoadAsset() { modelManager.loadingBunles.Add(ABName); /*while (!Caching.ready) * yield return null; * * WWW www = WWW.LoadFromCacheOrDownload(BundleFullURL + ABName, 1); * yield return www; * * if (!string.IsNullOrEmpty(www.error)) * { * preloader.LoadPercent(www); * Debug.Log(www.error); * yield return null; * } * AssetBundle bundle = www.assetBundle; * if (bundle.Contains(AssetName)) * { * Instantiate(bundle.LoadAssetAsync(AssetName).asset, gameObject.transform); * modelManager.bundles.Add(bundle); * modelManager.loadingBunles.Remove(ABName); * mover.modelName = ABName; * Debug.Log("is OBJ"); * preloader.Loaded(); * } * else * { * Debug.Log("Check asset name"); * }*/ #if UNITY_IOS BundleFullURL = PlayerPrefs.GetString("ApiUrl") + "/media/3d/" + ABName + "/ios/bundle"; #endif #if PLATFORM_ANDROID BundleFullURL = PlayerPrefs.GetString("ApiUrl") + "/media/3d/" + ABName + "/android/bundle"; #endif Debug.Log("Load Bundle Path = " + BundleFullURL); CachedAssetBundle cab = new CachedAssetBundle(ABName, new Hash128(0, 0)); using (UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(BundleFullURL, cab)) { preloader.LoadPercent(uwr); yield return(uwr.SendWebRequest()); if (uwr.isNetworkError || uwr.isHttpError) { Debug.Log(uwr.error); preloader.CantLoad(); preloader.Loaded(); GetComponent <Collider>().enabled = false; GetComponent <Mover>().enabled = false; } else { // Get downloaded asset bundle AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr); if (bundle.Contains(AssetName)) { Instantiate(bundle.LoadAssetAsync(AssetName).asset, gameObject.transform); modelManager.bundles.Add(bundle); modelManager.loadingBunles.Remove(ABName); mover.modelName = ABName; Debug.Log("is OBJ"); preloader.Loaded(); } else { Debug.Log("Check asset name"); preloader.CantLoad(); preloader.Loaded(); GetComponent <Collider>().enabled = false; GetComponent <Mover>().enabled = false; } } } }
private IEnumerator Download(AssetBundleDownloadCommand cmd, int retryCount) { var uri = baseUri + cmd.BundleName; UnityWebRequest req; if (cachingDisabled || (cmd.Version <= 0 && cmd.Hash == DEFAULT_HASH)) { Debug.Log(string.Format("GetAssetBundle [{0}].", uri)); #if UNITY_2018_1_OR_NEWER req = UnityWebRequestAssetBundle.GetAssetBundle(uri); #else req = UnityWebRequest.GetAssetBundle(uri); #endif } else if (cmd.Hash == DEFAULT_HASH) { Debug.Log(string.Format("GetAssetBundle [{0}] v[{1}] [{2}].", Caching.IsVersionCached(uri, new Hash128(0, 0, 0, cmd.Version)) ? "cached" : "uncached", cmd.Version, uri)); #if UNITY_2018_1_OR_NEWER req = UnityWebRequestAssetBundle.GetAssetBundle(uri, cmd.Version, 0); #else req = UnityWebRequest.GetAssetBundle(uri, cmd.Version, 0); #endif } else { Debug.Log(string.Format("GetAssetBundle [{0}] [{1}] [{2}].", Caching.IsVersionCached(uri, cmd.Hash) ? "cached" : "uncached", uri, cmd.Hash)); #if UNITY_2018_1_OR_NEWER req = UnityWebRequestAssetBundle.GetAssetBundle(uri, cmd.Hash, 0); #else req = UnityWebRequest.GetAssetBundle(uri, cmd.Hash, 0); #endif } #if UNITY_2017_2_OR_NEWER req.SendWebRequest(); #else req.Send(); #endif while (!req.isDone) { yield return(null); } #if UNITY_2017_1_OR_NEWER var isNetworkError = req.isNetworkError; var isHttpError = req.isHttpError; #else var isNetworkError = req.isError; var isHttpError = (req.responseCode < 200 || req.responseCode > 299) && req.responseCode != 0; // 0 indicates the cached version may have been downloaded. If there was an error then req.isError should have a non-0 code. #endif if (isHttpError) { Debug.LogError(string.Format("Error downloading [{0}]: [{1}] [{2}]", uri, req.responseCode, req.error)); if (retryCount < MAX_RETRY_COUNT && RETRY_ON_ERRORS.Contains(req.responseCode)) { Debug.LogWarning(string.Format("Retrying [{0}] in [{1}] seconds...", uri, RETRY_WAIT_PERIOD)); req.Dispose(); activeDownloads--; yield return(new WaitForSeconds(RETRY_WAIT_PERIOD)); InternalHandle(Download(cmd, retryCount + 1)); yield break; } } AssetBundle bundle; if (isNetworkError) { Debug.LogError(string.Format("Error downloading [{0}]: [{1}]", uri, req.error)); bundle = null; } else { bundle = DownloadHandlerAssetBundle.GetContent(req); } if (!isNetworkError && !isHttpError && string.IsNullOrEmpty(req.error) && bundle == null) { Debug.LogWarning(string.Format("There was no error downloading [{0}] but the bundle is null. Assuming there's something wrong with the cache folder, retrying with cache disabled now and for future requests...", uri)); cachingDisabled = true; req.Dispose(); activeDownloads--; yield return(new WaitForSeconds(RETRY_WAIT_PERIOD)); InternalHandle(Download(cmd, retryCount + 1)); yield break; } try { cmd.OnComplete(bundle); } finally { req.Dispose(); activeDownloads--; if (downloadQueue.Count > 0) { InternalHandle(downloadQueue.Dequeue()); } } }
//TODO: Refactor this behind its own object to provide download URL for character. /// <inheritdoc /> public async Task OnGameInitialized() { if (Logger.IsInfoEnabled) { Logger.Info("About to start downloading map data."); } //When we start the loading screen for the game //To know what world we should load we should CharacterSessionDataResponse characterSessionData = await CharacterService.GetCharacterSessionData(LocalCharacterData.CharacterId, AuthTokenRepo.RetrieveWithType()) .ConfigureAwait(false); if (!characterSessionData.isSuccessful) { Logger.Error($"Failed to query Character Session Data: {characterSessionData.ResultCode}:{(int)characterSessionData.ResultCode}"); return; } //TODO: Handle failure ProjectVersionStage.AssertAlpha(); //TODO: Handle throwing/error //We need to know the world the zone is it, so we can request a download URL for it. long worldId = await ZoneDataService.GetZoneWorld(characterSessionData.ZoneId) .ConfigureAwait(false); //With the worldid we can get the download URL. ContentDownloadURLResponse urlDownloadResponse = await ContentService.RequestWorldDownloadUrl(worldId, AuthTokenRepo.RetrieveWithType()) .ConfigureAwait(false); //TODO: Handle failure if (urlDownloadResponse.isSuccessful) { if (Logger.IsInfoEnabled) { Logger.Info($"Download URL: {urlDownloadResponse.DownloadURL}"); } //Can't do web request not on the main thread, sadly. await new UnityYieldAwaitable(); //TODO: Do we need to be on the main unity3d thread UnityWebRequestAsyncOperation asyncOperation = UnityWebRequestAssetBundle.GetAssetBundle(urlDownloadResponse.DownloadURL, 0).SendWebRequest(); //TODO: We should render these operations to the loading screen UI. asyncOperation.completed += operation => { AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(asyncOperation.webRequest); string[] paths = bundle.GetAllScenePaths(); foreach (string p in paths) { Debug.Log($"Found Scene in Bundle: {p}"); } AsyncOperation sceneAsync = SceneManager.LoadSceneAsync(System.IO.Path.GetFileNameWithoutExtension(paths.First())); sceneAsync.completed += operation1 => { //When the scene is finished loading we should cleanup the asset bundle //Don't clean up the WHOLE BUNDLE, just the compressed downloaded data bundle.Unload(false); //TODO: We need a way/system to reference the bundle later so it can be cleaned up inbetween scene loads. }; sceneAsync.allowSceneActivation = true; }; } }
void LoadTable(Uri uri, string assetBundleName, Hash128 hash, uint crc = 0) { Debug.Log(Caching.ready); //構造体生成 var cachedAssetBundle = new CachedAssetBundle(assetBundleName, hash); //全てのtableのキャッシュ削除 Caching.ClearAllCachedVersions(assetBundleName); //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(); // string text = prefab[0].ToString(); // table = JsonUtility.FromJson<AssetBundleTable>(text); // Debug.Log("バージョン" + table.Version); // int preVersion = PlayerPrefs.GetInt("DOWNLOAD", -1); // if (preVersion != table.Version) // { // Debug.Log("新しいバージョンがあります"); // } // LoadEnd(LOAD.TABLE); // }; //} //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("ダウンロード成功"); var bundle = DownloadHandlerAssetBundle.GetContent(request); var prefab = bundle.LoadAllAssets(); string text = prefab[0].ToString(); table = JsonUtility.FromJson <AssetBundleTable>(text); Debug.Log("バージョン" + table.Version); int preVersion = PlayerPrefs.GetInt("VERSION", -1); if (preVersion != table.Version) { Debug.Log("新しいバージョンがあります"); newDataObj.SetActive(true); } else { Debug.Log("同じバージョン"); downLoadObj.SetActive(true); LoadEnd(LOAD.TABLE); } } }; //} }
protected IEnumerator LoadAssetBundleWithDeps(string baseUrl, string hash, Action OnSuccess, Action OnFail) { string finalUrl = baseUrl + hash; if (failedRequestUrls.Contains(finalUrl)) { OnFail?.Invoke(); yield break; } yield return(WaitForConcurrentRequestsSlot()); RegisterConcurrentRequest(); #if (UNITY_EDITOR || UNITY_STANDALONE) asyncOp = Environment.i.platform.webRequest.GetAssetBundle(url: finalUrl, hash: Hash128.Compute(hash), disposeOnCompleted: false); #else //NOTE(Brian): Disable in build because using the asset bundle caching uses IDB. asyncOp = Environment.i.platform.webRequest.GetAssetBundle(url: finalUrl, disposeOnCompleted: false); #endif if (!DependencyMapLoadHelper.dependenciesMap.ContainsKey(hash)) { CoroutineStarter.Start(DependencyMapLoadHelper.GetDepMap(baseUrl, hash)); } yield return(DependencyMapLoadHelper.WaitUntilDepMapIsResolved(hash)); if (DependencyMapLoadHelper.dependenciesMap.ContainsKey(hash)) { using (var it = DependencyMapLoadHelper.dependenciesMap[hash].GetEnumerator()) { while (it.MoveNext()) { var dep = it.Current; var promise = new AssetPromise_AB(baseUrl, dep, containerTransform); AssetPromiseKeeper_AB.i.Keep(promise); dependencyPromises.Add(promise); } } } yield return(asyncOp); if (asyncOp.isDisposed) { OnFail?.Invoke(); yield break; } if (!asyncOp.isSucceded) { if (VERBOSE) { Debug.Log($"Request failed? {asyncOp.webRequest.error} ... {finalUrl}"); } failedRequestUrls.Add(finalUrl); OnFail?.Invoke(); asyncOp.Dispose(); yield break; } UnregisterConcurrentRequest(); foreach (var promise in dependencyPromises) { yield return(promise); } AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(asyncOp.webRequest); asyncOp.Dispose(); if (assetBundle == null || asset == null) { OnFail?.Invoke(); failedRequestUrls.Add(finalUrl); yield break; } asset.ownerAssetBundle = assetBundle; asset.assetBundleAssetName = assetBundle.name; assetBundlesLoader.MarkAssetBundleForLoad(asset, assetBundle, containerTransform, OnSuccess, OnFail); }
private IEnumerator DownloadResource() { var pip = _context.GetPIPLogic(); if (pip.IsTest()) { SetDownloadResourceResult(DownloadResourceResult.Ok, ""); yield break; } var data = pip.GetPIPData(); if (data == null) { SetDownloadResourceResult(DownloadResourceResult.Error, string.Format( "获取下载资源失败,请重新登陆\n【错误码{0}】)", NetworkStateErrorCode.DownloadResourcesFailCode)); yield break; } if (data.Assets != null && data.Assets.Length > 0) { var downloadAssetBundleInfo = new DownloadAssetBundleInfo(); downloadAssetBundleInfo.LoadType = DownloadAssetBundleInfo.DownloadType.Download; downloadAssetBundleInfo.TotalCount = data.Assets.Length; downloadAssetBundleInfo.CompleteCount = 0; foreach (var asset in data.Assets) { if (asset == null) { continue; } //已下载过相同版本 if (GetLastAssetVersion(asset.Asset) != null && GetLastAssetVersion(asset.Asset).Version == asset.Version) { continue; } _downloadAssetBundleInfo.Write(downloadAssetBundleInfo, Time.time); var req = UnityWebRequest.GetAssetBundle(asset.Url, (uint)asset.Version, (uint)0); req.SendWebRequest(); while (!req.isDone) { yield return(null); } if (req.isNetworkError || req.isHttpError) { MyLog.ErrorWithFrame(name, asset.Url + " download fail "); SetDownloadResourceResult(DownloadResourceResult.Error, string.Format( "下载资源失败,请重新登陆\n【错误码{0}】)", NetworkStateErrorCode.DownloadResourcesFailCode)); yield break; } try { var assetJson = JsonUtility.ToJson(asset); PrefsUtil.SetString(asset.Asset, assetJson); PrefsUtil.Flush(); downloadAssetBundleInfo.CompleteCount++; //只卸载没有被cache的临时的assetbundle if (!HasCached(asset.Asset)) { var assetBundle = DownloadHandlerAssetBundle.GetContent(req); if (assetBundle) { assetBundle.Unload(false); } } } catch (Exception e) { MyLog.ErrorWithFrame(name, asset.Url + " download fail with error :" + e); continue; } } } yield return(null); _downloadAssetBundleInfo.ClearAndInvalidate(Time.time); SetDownloadResourceResult(DownloadResourceResult.Ok, ""); MyLog.InfoWithFrame(name, " download all resource succ >>>>>>>>>>>>>>>>> UnloadAllAssetBundles >>>>>>>>>>>"); }