Beispiel #1
0
        public static Http GetAssetBundle(string uri, uint version, uint crc, System.Action <Http> onSuccess = null, System.Action <Exception> onFail = null)
        {
            Http http = new Http(UnityWebRequest.GetAssetBundle(uri, version, crc), onSuccess, onFail);

            return(http);
        }
        IEnumerator DoLoad(CultureInfo cultureInfo, Action <Dictionary <string, object> > onCompleted)
        {
            Dictionary <string, object> dict = new Dictionary <string, object>();

#if UNITY_2018_1_OR_NEWER
            using (UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(this.assetBundleUrl))
            {
                www.SendWebRequest();
                while (!www.isDone)
                {
                    yield return(null);
                }

                DownloadHandlerAssetBundle handler = (DownloadHandlerAssetBundle)www.downloadHandler;
                AssetBundle bundle = handler.assetBundle;
#elif UNITY_2017_1_OR_NEWER
            using (UnityWebRequest www = UnityWebRequest.GetAssetBundle(this.assetBundleUrl))
            {
                www.Send();
                while (!www.isDone)
                {
                    yield return(null);
                }

                DownloadHandlerAssetBundle handler = (DownloadHandlerAssetBundle)www.downloadHandler;
                AssetBundle bundle = handler.assetBundle;
#else
            using (WWW www = new WWW(this.assetBundleUrl))
            {
                while (!www.isDone)
                {
                    yield return(null);
                }

                AssetBundle bundle = www.assetBundle;
#endif
                try
                {
                    List <string> assetNames = new List <string>(bundle.GetAllAssetNames());

                    List <string> defaultPaths      = assetNames.FindAll(p => p.Contains("/default/"));
                    List <string> twoLetterISOpaths = assetNames.FindAll(p => p.Contains(string.Format("/{0}/", cultureInfo.TwoLetterISOLanguageName)));
                    List <string> paths             = assetNames.FindAll(p => p.Contains(string.Format("/{0}/", cultureInfo.Name)));

                    FillData(dict, bundle, defaultPaths, cultureInfo);
                    FillData(dict, bundle, twoLetterISOpaths, cultureInfo);
                    FillData(dict, bundle, paths, cultureInfo);
                }
                finally
                {
                    try
                    {
                        if (bundle != null)
                        {
                            bundle.Unload(true);
                        }
                    }
                    catch (Exception) { }

                    if (onCompleted != null)
                    {
                        onCompleted(dict);
                    }
                }
            }
        }
Beispiel #3
0
 internal override void Load()
 {
     _request = cache ? UnityWebRequest.GetAssetBundle(name, hash, 0) : UnityWebRequest.GetAssetBundle(name);
     _request.SendWebRequest();
     loadState = LoadState.LoadAssetBundle;
 }
Beispiel #4
0
 public void LoadFromDownload(string url, uint crc)
 {
     webRequest = UnityWebRequest.GetAssetBundle(url, crc);
 }
        protected override IEnumerator DoLoadAssetBundle(IProgressPromise <float, AssetBundle> promise)
        {
            if (this.BundleInfo.IsEncrypted)
            {
                promise.UpdateProgress(0f);
                promise.SetException(new NotSupportedException(string.Format("The data of the AssetBundle named '{0}' is encrypted,use the CryptographBundleLoader to load,please.", this.BundleInfo.Name)));
                yield break;
            }

            AssetBundle assetBundle;
            string      path = this.GetAbsoluteUri();

#if UNITY_ANDROID && !UNITY_2017_1_OR_NEWER
            if (this.Uri.Scheme.Equals("jar", StringComparison.OrdinalIgnoreCase))
            {
                using (WWW www = useCache ? WWW.LoadFromCacheOrDownload(path, this.BundleInfo.Hash) : new WWW(path))
                {
                    while (!www.isDone)
                    {
                        if (www.progress >= 0)
                        {
                            promise.UpdateProgress(www.progress);
                        }
                        yield return(null);
                    }

                    if (!string.IsNullOrEmpty(www.error))
                    {
                        promise.SetException(new Exception(string.Format("Failed to load the AssetBundle '{0}' at the address '{1}'.Error:{2}", this.BundleInfo.Name, path, www.error)));
                        yield break;
                    }

                    assetBundle = www.assetBundle;
                }
            }
            else
#endif
            {
#if UNITY_2018_1_OR_NEWER
                using (UnityWebRequest www = useCache ? UnityWebRequestAssetBundle.GetAssetBundle(path, this.BundleInfo.Hash, 0) : UnityWebRequestAssetBundle.GetAssetBundle(path))
                {
                    www.SendWebRequest();
#else
                using (UnityWebRequest www = useCache ? UnityWebRequest.GetAssetBundle(path, this.BundleInfo.Hash, 0) : UnityWebRequest.GetAssetBundle(path))
                {
                    www.Send();
#endif
                    while (!www.isDone)
                    {
                        if (www.downloadProgress >= 0)
                        {
                            promise.UpdateProgress(www.downloadProgress);
                        }
                        yield return(null);
                    }

                    if (!string.IsNullOrEmpty(www.error))
                    {
                        promise.SetException(new Exception(string.Format("Failed to load the AssetBundle '{0}' at the address '{1}'.Error:{2}", this.BundleInfo.Name, path, www.error)));
                        yield break;
                    }

                    DownloadHandlerAssetBundle handler = (DownloadHandlerAssetBundle)www.downloadHandler;
                    assetBundle = handler.assetBundle;
                }
            }

            if (assetBundle == null)
            {
                promise.SetException(new Exception(string.Format("Failed to load the AssetBundle '{0}' at the address '{1}'.", this.BundleInfo.Name, path)));
                yield break;
            }

            promise.UpdateProgress(1f);
            promise.SetResult(assetBundle);
        }
    }
Beispiel #6
0
        protected override IEnumerator DoDownloadBundles(IProgressPromise <Progress, bool> promise, List <BundleInfo> bundles)
        {
            long              totalSize      = 0;
            long              downloadedSize = 0;
            Progress          progress       = new Progress();
            List <BundleInfo> list           = new List <BundleInfo>();

            for (int i = 0; i < bundles.Count; i++)
            {
                var info = bundles[i];
                totalSize += info.FileSize;
                if (BundleUtil.Exists(info))
                {
                    downloadedSize += info.FileSize;
                    continue;
                }
                list.Add(info);
            }

            progress.TotalCount     = bundles.Count;
            progress.CompletedCount = bundles.Count - list.Count;
            progress.TotalSize      = totalSize;
            progress.CompletedSize  = downloadedSize;
            yield return(null);

            List <KeyValuePair <BundleInfo, UnityWebRequest> > tasks = new List <KeyValuePair <BundleInfo, UnityWebRequest> >();

            for (int i = 0; i < list.Count; i++)
            {
                BundleInfo bundleInfo = list[i];

                UnityWebRequest www;
                if (useCache && !bundleInfo.IsEncrypted)
                {
#if UNITY_2018_1_OR_NEWER
                    www = UnityWebRequestAssetBundle.GetAssetBundle(GetAbsoluteUri(bundleInfo.Filename), bundleInfo.Hash, 0);
#else
                    www = UnityWebRequest.GetAssetBundle(GetAbsoluteUri(bundleInfo.Filename), bundleInfo.Hash, 0);
#endif
                }
                else
                {
                    www = new UnityWebRequest(GetAbsoluteUri(bundleInfo.Filename));
                    www.downloadHandler = new DownloadHandlerBuffer();
                }

#if UNITY_2018_1_OR_NEWER
                www.SendWebRequest();
#else
                www.Send();
#endif
                tasks.Add(new KeyValuePair <BundleInfo, UnityWebRequest>(bundleInfo, www));

                while (tasks.Count >= this.MaxTaskCount || (i == list.Count - 1 && tasks.Count > 0))
                {
                    long tmpSize = 0;
                    for (int j = tasks.Count - 1; j >= 0; j--)
                    {
                        var             task        = tasks[j];
                        BundleInfo      _bundleInfo = task.Key;
                        UnityWebRequest _www        = task.Value;

                        if (!_www.isDone)
                        {
                            tmpSize += (long)Math.Max(0, _www.downloadedBytes);//the UnityWebRequest.downloadedProgress has a bug in android platform
                            continue;
                        }

                        progress.CompletedCount += 1;
                        tasks.RemoveAt(j);
                        downloadedSize += _bundleInfo.FileSize;
                        if (!string.IsNullOrEmpty(_www.error))
                        {
                            promise.SetException(new Exception(_www.error));
                            if (log.IsErrorEnabled)
                            {
                                log.ErrorFormat("Downloads AssetBundle '{0}' failure from the address '{1}'.Reason:{2}", _bundleInfo.FullName, GetAbsoluteUri(_bundleInfo.Filename), _www.error);
                            }
                            yield break;
                        }

                        try
                        {
                            if (useCache && !bundleInfo.IsEncrypted)
                            {
                                AssetBundle bundle = ((DownloadHandlerAssetBundle)_www.downloadHandler).assetBundle;
                                if (bundle != null)
                                {
                                    bundle.Unload(true);
                                }
                            }
                            else
                            {
                                string   fullname = BundleUtil.GetStorableDirectory() + _bundleInfo.Filename;
                                FileInfo info     = new FileInfo(fullname);
                                if (info.Exists)
                                {
                                    info.Delete();
                                }

                                if (!info.Directory.Exists)
                                {
                                    info.Directory.Create();
                                }

                                File.WriteAllBytes(info.FullName, _www.downloadHandler.data);
                            }
                        }
                        catch (Exception e)
                        {
                            promise.SetException(e);
                            if (log.IsErrorEnabled)
                            {
                                log.ErrorFormat("Downloads AssetBundle '{0}' failure from the address '{1}'.Reason:{2}", _bundleInfo.FullName, GetAbsoluteUri(_bundleInfo.Filename), e);
                            }
                            yield break;
                        }
                    }

                    progress.CompletedSize = downloadedSize + tmpSize;
                    promise.UpdateProgress(progress);

                    yield return(null);
                }
            }
            promise.SetResult(true);
        }
Beispiel #7
0
 public void LoadFromCacheOrDownload(string url)
 {
     webRequest = UnityWebRequest.GetAssetBundle(url, 1u, 0u);
 }
    internal IEnumerator DownloadAndCache(string assetBundleName, System.Action <bool> result)
    {
        if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor)

        {
            _tempAssetBundle = null;
            foreach (var assetBundle in _myBundles)
            {
                if (assetBundle.Key == assetBundleName)//nếu đã load rồi
                {
                    result(true);
                    yield return(null);
                }
            }
            if (_tempAssetBundle == null)
            {
                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 www = UnityWebRequest.Get(myServer + assetBundleName + ".manifest?r=" + (UnityEngine.Random.value * 9999999));
                StartCoroutine(LoadingResource.Instance.LoadDataProgress(www));
                //Debug.Log("Loading manifest:" + myServer + assetBundleName + ".manifest");

                // wait for load to finish
                yield return(www.Send());

                // if received error, exit
                if (www.isError == true)
                {
                    Debug.LogError("www error:" + www.error);
                    yield break;
                }

                // create empty hash string
                Hash128 hashString = (default(Hash128));// new Hash128(0, 0, 0, 0);

                // check if received data contains 'ManifestFileVersion'
                if (www.downloadHandler.text.Contains("ManifestFileVersion"))
                {
                    // extract hash string from the received data, should add some error checking here
                    var hashRow = www.downloadHandler.text.ToString().Split("\n".ToCharArray())[5];
                    hashString = Hash128.Parse(hashRow.Split(':')[1].Trim());

                    if (hashString.isValid == true)
                    {
                        if (Caching.IsVersionCached(myServer + assetBundleName, hashString) == true)
                        {
                            //Debug.Log("Bundle with this hash is already cached!");
                        }
                        else
                        {
                            Debug.Log("No cached version founded for this hash..");
                        }
                    }
                    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': " + myServer + assetBundleName + ".manifest");
                    yield break;
                }

                // now download the actual bundle, with hashString parameter it uses cached version if available
                www = UnityWebRequest.GetAssetBundle(myServer + assetBundleName + "?r=" + (UnityEngine.Random.value * 9999999), hashString, 0);
                StartCoroutine(LoadingResource.Instance.LoadDataProgress(www));
                // wait for load to finish
                yield return(www.Send());

                if (www.isError)
                {
                    Debug.Log(www.error);
                    result(false);
                    yield return(null);
                }
                else
                {
                    _tempAssetBundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;
                    //PlayerPrefs.SetInt(Constant.VERSION, 5);
                }

                //_tempAssetBundle.Unload(false);
            }

            _myBundles.Add(assetBundleName, _tempAssetBundle);
            result(true);
        }
    }
Beispiel #9
0
    IEnumerator LoadUIPackage()
    {
        string url = Application.streamingAssetsPath.Replace("\\", "/") + "/fairygui-examples/bundleusage.ab";

        if (Application.platform != RuntimePlatform.Android)
        {
            url = "file:///" + url;
        }

#if UNITY_5_4_OR_NEWER
#if UNITY_2018_1_OR_NEWER
        UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(url);
#else
        UnityWebRequest www = UnityWebRequest.GetAssetBundle(url);
#endif
#if UNITY_2017_2_OR_NEWER
        yield return(www.SendWebRequest());
#else
        yield return(www.Send());
#endif

        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.");
                yield return(0);
            }
            UIPackage.AddPackage(bundle);

            _mainView = UIPackage.CreateObject("BundleUsage", "Main").asCom;
            _mainView.fairyBatching = true;
            _mainView.SetSize(GRoot.inst.width, GRoot.inst.height);
            _mainView.AddRelation(GRoot.inst, RelationType.Size);

            GRoot.inst.AddChild(_mainView);
            _mainView.GetTransition("t0").Play();
        }
        else
        {
            Debug.LogError(www.error);
        }
    }

    void OnKeyDown(EventContext context)
    {
        if (context.inputEvent.keyCode == KeyCode.Escape)
        {
            Application.Quit();
        }
    }
}
Beispiel #10
0
 public static IObservable <AssetBundle> GetAssetBundle(string url, Hash128 hash128, uint crc, Hash headers = null, IProgress <float> progress = null)
 {
     return(ObservableUnity.FromCoroutine <AssetBundle>((observer, cancellation) =>
                                                        FetchAssetBundle(UnityWebRequest.GetAssetBundle(url, hash128, crc), (headers ?? new Hash()), observer, progress, cancellation)));
 }
Beispiel #11
0
        private IEnumerator DownloadAssetBundle(
            string bundleName,
            string connectionId,
            Dictionary <string, string> requestHeader,
            string url,
            uint crc,
            Hash128 hash,
            Action <string, int, Dictionary <string, string>, AssetBundle> succeeded,
            Action <string, int, string, Dictionary <string, string> > failed,
            long limitTick
            )
        {
            var alreadyStorageCached = false;

            if (Caching.IsVersionCached(url, hash))
            {
                alreadyStorageCached = true;
            }

            using (var request = UnityWebRequest.GetAssetBundle(url, hash, crc)) {
                if (requestHeader != null)
                {
                    foreach (var kv in requestHeader)
                    {
                        request.SetRequestHeader(kv.Key, kv.Value);
                    }
                }

                var p = request.Send();

                while (!p.isDone)
                {
                    yield return(null);

                    // check timeout.
                    if (limitTick != 0 && limitTick < DateTime.UtcNow.Ticks)
                    {
                        request.Abort();
                        failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, "timeout to download bundle:" + bundleName, new Dictionary <string, string>());
                        yield break;
                    }
                }

                while (!request.isDone)
                {
                    yield return(null);
                }

                var responseCode    = (int)request.responseCode;
                var responseHeaders = request.GetResponseHeaders();

                if (request.isError)
                {
                    failed(connectionId, responseCode, request.error, responseHeaders);
                    yield break;
                }

                if (alreadyStorageCached)
                {
                    // set response code to 200 manually if already cached and succeeded to load from cache.
                    // sadly, in this case, the code is not 200 by default.
                    responseCode = 200;
                }
                else
                {
                    if (200 <= responseCode && responseCode <= 299)
                    {
                        // do nothing.
                    }
                    else
                    {
                        failed(connectionId, responseCode, "failed to load assetBundle. downloaded bundle:" + bundleName + " was not downloaded.", responseHeaders);
                        yield break;
                    }
                }

                var dataHandler = (DownloadHandlerAssetBundle)request.downloadHandler;

                var assetBundle = dataHandler.assetBundle;

                if (assetBundle == null)
                {
                    responseCode = CODE_CRC_MISMATCHED;
                    failed(connectionId, responseCode, "failed to load assetBundle. downloaded bundle:" + bundleName + ", requested crc was not matched.", responseHeaders);
                    yield break;
                }

                // wait for cache.
                while (!Caching.IsVersionCached(url, hash))
                {
                    yield return(null);
                }

                succeeded(connectionId, responseCode, responseHeaders, assetBundle);
            }
        }
        private IEnumerator Donwload()
        {
            var url = preUrl + postUrl;

            if (String.IsNullOrEmpty(postUrl))
            {
                Debug.LogError("このURLは無効です");
                yield break;
            }
            else
            {
                Debug.Log("ダウンロード先:\n" + url);
            }

            using (var request = UnityWebRequest.GetAssetBundle(url))
            {
                yield return(request.Send());

                while (!request.isDone)
                {
                    if (request.isError)
                    {
                        Debug.LogError(request.error);
                        yield break;
                    }

                    yield return(null);
                }

                if (request.responseCode != 200)
                {
                    if (request.responseCode == 404)
                    {
                        Debug.LogError("そのURLは無効です");
                    }
                    else
                    {
                        Debug.LogError("エラーです");
                    }

                    yield break;
                }

                var bundle = ((DownloadHandlerAssetBundle)request.downloadHandler).assetBundle;
                if (bundle == null)
                {
                    yield break;
                }

                if (dataBase == null)
                {
                    Debug.LogError("設定ファイルが存在しません");
                    yield break;
                }

                var allAssets = bundle.LoadAllAssets();

                var prefabAssets = allAssets.Where(obj => obj is GameObject)
                                   .Cast <GameObject>()
                                   .ToArray();
                if (prefabAssets.Any())

                {
                    dataBase.LoadAssetBundle(AssetType.Prefab, prefabAssets);
                }

                var materialAssets = allAssets.Where(obj => obj is Material)
                                     .Cast <Material>()
                                     .ToArray();
                if (materialAssets.Any())

                {
                    dataBase.LoadAssetBundle(AssetType.Material, materialAssets);
                }

                var spriteAssets = allAssets.Where(obj => obj is Sprite)
                                   .Cast <Sprite>()
                                   .ToArray();

                if (spriteAssets.Any())
                {
                    dataBase.LoadAssetBundle(AssetType.Sprite, spriteAssets);
                }

                var soundAssets = allAssets.Where(obj => obj is AudioClip)
                                  .Cast <AudioClip>()
                                  .ToArray();
                if (soundAssets.Any())
                {
                    dataBase.LoadAssetBundle(AssetType.Sound, soundAssets);
                }

                var otherAssets = allAssets.Where(obj => !(obj is GameObject))
                                  .Where(obj => !(obj is Material))
                                  .Where(obj => !(obj is Sprite))
                                  .Where(obj => !(obj is AudioClip))
                                  .ToArray();

                if (otherAssets.Any())
                {
                    dataBase.LoadAssetBundle(AssetType.Other, otherAssets);
                }

                AssetBundleView.Open();
                bundle.Unload(false);
            }
        }
    // Use this for initialization
    IEnumerator Start()
    {
        string path = @"file:///F:\Test\AssetBundleProject\AssetBundles\cubewall.unity3d";
        //AssetBundle ab = AssetBundle.LoadFromFile("AssetBundles/cubewall.unity3d");
        //GameObject cubePrefab = ab.LoadAsset<GameObject>("CubeWall");
        //Instantiate(cubePrefab);
        //Object[] objs = ab.LoadAllAssets();
        //foreach(Object o in objs)
        //{
        //    Instantiate(o);
        //}

        //第一种加载AB的方式 LoadFromMemoryAsync
        //AssetBundleCreateRequest request =  AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path));
        //yield return request;
        //AssetBundle ab = request.assetBundle;

        //AssetBundle ab = AssetBundle.LoadFromMemory(File.ReadAllBytes(path));

        // 第二种加载AB的方式 LoadFromFile
        //AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);
        //yield return request;
        //AssetBundle ab = request.assetBundle;

        // 第三种加载AB的方式 www
        //while (Caching.ready == false)
        //{
        //    yield return null;
        //}

        ////WWW www = WWW.LoadFromCacheOrDownload(path, 1);
        //WWW www = WWW.LoadFromCacheOrDownload(@"http://localhost/AssetBundles/cubewall.unity3d", 1);

        //yield return www;
        //if (string.IsNullOrEmpty(www.error)== false)
        //{
        //    Debug.Log(www.error);
        //    yield break;
        //}
        //AssetBundle ab = www.assetBundle;

        //第四种方式 使用UnityWebRequest

        //string url = @"file:///F:\Test\AssetBundleProject\AssetBundles\cubewall.unity3d";
        string url = @"http://localhost/AssetBundles/cubewall.unity3d";

        UnityWebRequest request = UnityWebRequest.GetAssetBundle(url);

        yield return(request.Send());

        //AssetBundle ab = DownloadHandlerAssetBundle.GetContent (request);
        AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;

        // 使用里面的资源
        GameObject cubePrefab = ab.LoadAsset <GameObject>("CubeWall");

        Instantiate(cubePrefab);

        AssetBundle         maifestAB = AssetBundle.LoadFromFile("AssetBundles/assetBundles");
        AssetBundleManifest manifest  = maifestAB.LoadAsset <AssetBundleManifest>("AssetBundleManifest");

        //foreach(string name in manifest.GetAllAssetBundles())
        //{
        //    print(name);
        //}
        string[] strs = manifest.GetAllDependencies("cubewall.unity3d");
        foreach (string item in strs)
        {
            print(item);
            AssetBundle.LoadFromFile("AssetBundles/" + item);
        }
    }
Beispiel #14
0
        /// <summary>
        /// Downloads the asset bundle.
        /// </summary>
        /// <returns>The asset bundle.</returns>
        /// <param name="url">URL.</param>
        /// <param name="version">Version.</param>
        /// <param name="finished">Finished.</param>
        public IEnumerator DownloadAssetBundle(string url, int version, FinishedDelegate finished)
        {
            string keyName = url + version.ToString();

            if (dictionaryAssetBundleRef.ContainsKey(keyName))
            {
                if (finished != null)
                {
                    finished(null);
                }

                yield return(null);
            }
            else
            {
                while (!Caching.ready)
                {
                    yield return(null);
                }

#if UNITY_5_4_OR_NEWER
                uint v = Convert.ToUInt32(version);
                using (UnityWebRequest www = UnityWebRequest.GetAssetBundle(url, v, 0)) {
                    yield return(www.Send());

                    while (!www.isDone)
                    {
                        progress = www.downloadProgress;
                        yield return(null);
                    }

                    if (!www.isError)
                    {
                        AssetBundleRef assetBundleRef = new AssetBundleRef(url, version);
                        assetBundleRef.assetBundle = DownloadHandlerAssetBundle.GetContent(www);
                        dictionaryAssetBundleRef.Add(keyName, assetBundleRef);

                        yield return(null);
                    }

                    if (finished != null)
                    {
                        finished(www);
                    }

                    progress = 1f;
                }
#else
                using (WWW www = WWW.LoadFromCacheOrDownload(url, version)) {
                    while (!www.isDone)
                    {
                        progress = www.progress;
                        yield return(null);
                    }

                    if (www.error == null)
                    {
                        AssetBundleRef assetBundleRef = new AssetBundleRef(url, version);
                        assetBundleRef.assetBundle = www.assetBundle;
                        dictionaryAssetBundleRef.Add(keyName, assetBundleRef);

                        yield return(null);
                    }

                    if (finished != null)
                    {
                        finished(www);
                    }

                    progress = 1f;
                    www.Dispose();
                }
#endif
            }
        }
Beispiel #15
0
        /// <summary>
        /// Update manifest.
        /// Compare manifests and delete old cached bundles.
        /// Starts download of manifest asset bundle.
        /// Returns the manifest asset bundle downolad operation object.
        /// </summary>
        /// <param name="newManifest">Asset bundle manifest.</param>
        static void SetManifest(AssetBundleManifest newManifest)
        {
            if (!newManifest)
            {
                Debug.LogErrorFormat("{0}マニフェスト更新 失敗 : {1}", kLog, patch);
                return;
            }

            var oldManifest = AssetManager.manifest;

            AssetManager.manifest = newManifest;

            if (oldManifest)
            {
                var oldBundles = new HashSet <string>(oldManifest.GetAllAssetBundles());
                var newBundles = new HashSet <string>(newManifest.GetAllAssetBundles());

                // 新規
                var sb    = new StringBuilder();
                var array = newBundles.Except(oldBundles).ToArray();
                sb.AppendFormat("[Added] {0}\n", array.Length);
                foreach (var bundleName in array)
                {
                    sb.AppendFormat("  > {0} ({1})\n", bundleName, newManifest.GetAssetBundleHash(bundleName).ToString().Substring(0, 4));
                }

                // 削除
                array = oldBundles.Except(newBundles).ToArray();
                sb.AppendFormat("\n[Deleted : キャッシュは削除されます] {0}\n", array.Length);
                foreach (var bundleName in array)
                {
                    sb.AppendFormat("  > {0} ({1})\n", bundleName, oldManifest.GetAssetBundleHash(bundleName).ToString().Substring(0, 4));
                }


                // 更新
                array = oldBundles
                        .Intersect(newBundles)
                        .Select(name => new { name = name, oldHash = oldManifest.GetAssetBundleHash(name), newHash = newManifest.GetAssetBundleHash(name), })
                        .Where(x => x.oldHash != x.newHash)
                        .Select(x => string.Format("{0} ({1} -> {2})", x.name, x.oldHash.ToString().Substring(0, 4), x.newHash.ToString().Substring(0, 4)))
                        .ToArray();
                sb.AppendFormat("\n[Updated : 古いキャッシュは削除されます] {0}\n", array.Length);
                foreach (var bundleName in array)
                {
                    sb.AppendLine("  > " + bundleName);
                }

#if UNITY_2017_1_OR_NEWER
                // 削除
                foreach (var name in oldBundles.Except(newBundles))
                {
                    UnloadAssetBundleInternal(name);
                    Caching.ClearAllCachedVersions(name);
                    Debug.LogFormat("{0}キャッシュ削除 : {1}", kLog, name);
                }

                // 更新
                foreach (var name in newBundles)
                {
                    UnloadAssetBundleInternal(name);
                    Caching.ClearOtherCachedVersions(name, newManifest.GetAssetBundleHash(name));
                    Debug.LogFormat("{0}キャッシュ削除 : {1}", kLog, name);
                }
#else
                foreach (var name in oldBundles.Where(newBundles.Contains))
                {
                    var oldHash = oldManifest.GetAssetBundleHash(name);
                    var newHash = newManifest.GetAssetBundleHash(name);

                    // The bundle has removed or changed. Need to delete cached bundle.
                    if (oldHash != newHash)
                    {
                        UnloadAssetBundleInternal(name);
                        if (Caching.IsVersionCached(name, oldHash))
                        {
                            Debug.LogFormat("{0}キャッシュ削除 : {1}({2})", kLog, name, oldHash.ToString().Substring(0, 4));
                            var request = UnityWebRequest.GetAssetBundle(name, oldHash, uint.MaxValue);
                            request.Send();
                            request.Abort();
                        }
                    }
                }
#endif
                Debug.LogFormat("{0}マニフェスト更新 完了 : {2}\n変更は以下の通りです:\n{1}", kLog, sb, patch);
            }
            else
            {
                var newBundles = newManifest.GetAllAssetBundles();

                // 新規
                var sb = new StringBuilder();
                sb.AppendFormat("[Added] {0}\n", newBundles.Length);
                foreach (var bundleName in newBundles)
                {
                    sb.AppendFormat("  > {0} ({1})\n", bundleName, newManifest.GetAssetBundleHash(bundleName).ToString().Substring(0, 4));
                }
                Debug.LogFormat("{0}マニフェスト更新 完了 : {2}\n変更は以下の通りです:\n{1}", kLog, sb, patch);
            }
            instance.storedPatch = patch;
        }
        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)
            {
                if (cachingDisabled)
                {
                    Debug.LogWarning(string.Format("There was no error downloading [{0}] but the bundle is null.  Caching has already been disabled, not sure there's anything else that can be done.  Returning...", uri));
                }
                else
                {
                    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());
                }
            }
        }