示例#1
0
        IResources GetResources()
        {
            if (this.resources != null)
            {
                return(this.resources);
            }

            /* Create a BundleManifestLoader. */
            IBundleManifestLoader manifestLoader = new BundleManifestLoader();

            /* Loads BundleManifest. */
            BundleManifest manifest = manifestLoader.Load(BundleUtil.GetStorableDirectory() + BundleSetting.ManifestFilename);

            //manifest.ActiveVariants = new string[] { "", "sd" };
            //manifest.ActiveVariants = new string[] { "", "hd" };

            /* Create a PathInfoParser. */
            IPathInfoParser pathInfoParser = new AutoMappingPathInfoParser(manifest);

            /* Use a custom BundleLoaderBuilder */
            ILoaderBuilder builder = new CustomBundleLoaderBuilder(new Uri(BundleUtil.GetReadOnlyDirectory()), false);

            /* Create a BundleManager */
            IBundleManager manager = new BundleManager(manifest, builder);

            /* Create a BundleResources */
            this.resources = new BundleResources(pathInfoParser, manager);
            return(this.resources);
        }
        public AssetBundleManager(string bundleDownladerUri, AssetPath assetPath = AssetPath.streamingAssetsPath)
        {
            switch (assetPath)
            {
            case AssetPath.streamingAssetsPath:
                uriString = BundleUtil.GetReadOnlyDirectory();
                break;

            case AssetPath.persistentDataPath:
                uriString = BundleUtil.GetStorableDirectory();
                break;

            case AssetPath.temporaryCachePath:
                uriString = BundleUtil.GetTemporaryCacheDirectory();
                break;
            }

            this.resources = null;
            if (string.IsNullOrEmpty(bundleDownladerUri))
            {
                return;
            }

            Uri baseUri = new Uri(bundleDownladerUri);

            this.downloader = new WWWDownloader(baseUri, false);
        }
示例#3
0
        public void check()
        {
            var  dir      = BundleUtil.GetStorableDirectory() + name + "/";
            var  nv       = version.Split('.');
            bool nv_vaild = nv.Length >= 2;
            int  nm       = Convert.ToInt32(nv [0]);
            int  nn       = Convert.ToInt32(nv [1]);

            bool clean = true;
            bool up    = true;
            var  file  = dir + "version.txt";

            if (File.Exists(file))
            {
                var  old      = File.ReadAllText(file);
                var  ov       = old.Split('.');
                bool ov_valid = ov.Length >= 2;
                int  om       = Convert.ToInt32(ov [0]);
                int  on       = Convert.ToInt32(ov [1]);

                if (ov_valid && om == nm)
                {
                    clean = false;
                }

                if (ov_valid && on >= nn)
                {
                    up = false;
                }
            }

            shouldClean  = clean;
            shouldUpdate = up;
        }
示例#4
0
        IEnumerator Download()
        {
            this.downloading = true;
            try
            {
                IProgressResult <Progress, BundleManifest> manifestResult = this.downloader.DownloadManifest(BundleSetting.ManifestFilename);

                yield return(manifestResult.WaitForDone());

                if (manifestResult.Exception != null)
                {
                    Debug.LogFormat("Downloads BundleManifest failure.Error:{0}", manifestResult.Exception);
                    yield break;
                }

                BundleManifest manifest = manifestResult.Result;

                IProgressResult <float, List <BundleInfo> > bundlesResult = this.downloader.GetDownloadList(manifest);
                yield return(bundlesResult.WaitForDone());

                List <BundleInfo> bundles = bundlesResult.Result;

                if (bundles == null || bundles.Count <= 0)
                {
                    Debug.LogFormat("Please clear cache and remove StreamingAssets,try again.");
                    yield break;
                }

                IProgressResult <Progress, bool> downloadResult = this.downloader.DownloadBundles(bundles);
                downloadResult.Callbackable().OnProgressCallback(p =>
                {
                    Debug.LogFormat("Downloading {0:F2}KB/{1:F2}KB {2:F3}KB/S", p.GetCompletedSize(UNIT.KB), p.GetTotalSize(UNIT.KB), p.GetSpeed(UNIT.KB));
                });

                yield return(downloadResult.WaitForDone());

                if (downloadResult.Exception != null)
                {
                    Debug.LogFormat("Downloads AssetBundle failure.Error:{0}", downloadResult.Exception);
                    yield break;
                }

                Debug.Log("OK");

                if (this.resources != null)
                {
                    //update BundleManager's manifest
                    BundleManager manager = (this.resources as BundleResources).BundleManager as BundleManager;
                    manager.BundleManifest = manifest;
                }

#if UNITY_EDITOR
                UnityEditor.EditorUtility.OpenWithDefaultApp(BundleUtil.GetStorableDirectory());
#endif
            }
            finally
            {
                this.downloading = false;
            }
        }
示例#5
0
        public override BundleLoader Create(BundleManager manager, BundleInfo bundleInfo, BundleLoader[] dependencies)
        {
            //Customize the rules for finding assets.

            Uri loadBaseUri = this.BaseUri; //eg: http://your ip/bundles

            if (this.useCache && BundleUtil.ExistsInCache(bundleInfo))
            {
                //Load assets from the cache of Unity3d.
                loadBaseUri = this.BaseUri;
#if UNITY_5_4_OR_NEWER
                return(new UnityWebRequestBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager, this.useCache));
#else
                return(new WWWBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager, this.useCache));
#endif
            }

            if (BundleUtil.ExistsInStorableDirectory(bundleInfo))
            {
                //Load assets from the "Application.persistentDataPath/bundles" folder.
                /* Path: Application.persistentDataPath + "/bundles/" + bundleInfo.Filename  */
                loadBaseUri = new Uri(BundleUtil.GetStorableDirectory());
            }

#if !UNITY_WEBGL || UNITY_EDITOR
            else if (BundleUtil.ExistsInReadOnlyDirectory(bundleInfo))
            {
                //Load assets from the "Application.streamingAssetsPath/bundles" folder.
                /* Path: Application.streamingAssetsPath + "/bundles/" + bundleInfo.Filename */

                loadBaseUri = new Uri(BundleUtil.GetReadOnlyDirectory());
            }
#endif

            if (bundleInfo.IsEncrypted)
            {
                if (this.decryptor != null && bundleInfo.Encoding.Equals(decryptor.AlgorithmName))
                {
                    return(new CryptographBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager, decryptor));
                }

                throw new NotSupportedException(string.Format("Not support the encryption algorithm '{0}'.", bundleInfo.Encoding));
            }


            //Loads assets from an Internet address if it does not exist in the local directory.
#if UNITY_5_4_OR_NEWER
            if (this.IsRemoteUri(loadBaseUri))
            {
                return(new UnityWebRequestBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager, this.useCache));
            }
            else
            {
                return(new FileAsyncBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager));
            }
#else
            return(new WWWBundleLoader(new Uri(loadBaseUri, bundleInfo.Filename), bundleInfo, dependencies, manager, this.useCache));
#endif
        }
示例#6
0
        public void clean()
        {
            var dir = BundleUtil.GetStorableDirectory() + name + "/";

            if (Directory.Exists(dir))
            {
                Directory.Delete(dir, true);
                Directory.CreateDirectory(dir);
            }
        }
示例#7
0
    void SaveVersion(string name, string version)
    {
        var v    = BundleUtil.GetStorableDirectory() + name + "/version.txt";
        var info = new FileInfo(v);

        if (info.Exists)
        {
            info.Delete();
        }

        File.WriteAllText(info.FullName, version);
    }
    IResources CreateResources()
    {
        IResources resources = null;

#if UNITY_EDITOR
        if (SimulationSetting.IsSimulationMode)
        {
            LogManager.Log("Use SimulationResources. Run In Editor");

            /* Create a PathInfoParser. */
            //IPathInfoParser pathInfoParser = new SimplePathInfoParser("@");
            IPathInfoParser pathInfoParser = new SimulationAutoMappingPathInfoParser();

            /* Create a BundleManager */
            IBundleManager manager = new SimulationBundleManager();

            /* Create a BundleResources */
            resources = new SimulationResources(pathInfoParser, manager);
        }
        else
#endif
        {
            /* Create a BundleManifestLoader. */
            IBundleManifestLoader manifestLoader = new BundleManifestLoader();


            /* Loads BundleManifest. */
            BundleManifest manifest;
            manifest = manifestLoader.Load(BundleUtil.GetStorableDirectory() + BundleSetting.ManifestFilename);

            //manifest.ActiveVariants = new string[] { "", "sd" };
            //manifest.ActiveVariants = new string[] { "", "hd" };

            /* Create a PathInfoParser. */
            //IPathInfoParser pathInfoParser = new SimplePathInfoParser("@");
            IPathInfoParser pathInfoParser = new AutoMappingPathInfoParser(manifest);

            /* Create a BundleLoaderBuilder */
            ILoaderBuilder builder;
            builder = new WWWComplexLoaderBuilder(new Uri(BundleUtil.GetStorableDirectory()), false);

            /* Create a BundleManager */
            IBundleManager manager = new BundleManager(manifest, builder);

            /* Create a BundleResources */
            resources = new BundleResources(pathInfoParser, manager);
        }
        return(resources);
    }
示例#9
0
        void OnGUI()
        {
            if (!downloading)
            {
                GUILayout.Space(20);
                GUILayout.BeginHorizontal();
                GUILayout.Space(20);
                GUILayout.BeginVertical();
                if (GUILayout.Button("Clear persistentDataPath"))
                {
#if UNITY_2017_1_OR_NEWER
                    Caching.ClearCache();
#else
                    Caching.CleanCache();
#endif
                    BundleUtil.ClearStorableDirectory();
                }
#if UNITY_EDITOR
                if (GUILayout.Button("Remove StreamingAssets"))
                {
                    if (Directory.Exists(BundleUtil.GetReadOnlyDirectory()))
                    {
                        Directory.Delete(BundleUtil.GetReadOnlyDirectory(), true);
                    }
                    UnityEditor.AssetDatabase.Refresh();
                }
#endif
                GUILayout.Space(5);
                if (GUILayout.Button("Download AssetBundle"))
                {
                    StartCoroutine(Download());
                }

                if (GUILayout.Button("Load an asset"))
                {
                    if (!File.Exists(BundleUtil.GetStorableDirectory() + BundleSetting.ManifestFilename))
                    {
                        Debug.LogFormat("Please download assetbundles first,try again.");
                    }
                    else
                    {
                        this.LoadAsset("LoxodonFramework/BundleExamples/Models/Red/Red.prefab");
                    }
                }
                GUILayout.EndVertical();
                GUILayout.EndHorizontal();
            }
        }
示例#10
0
    public IEnumerator LoadGame(string name)
    {
        if (!gamesMap.ContainsKey(name))
        {
            Debug.Log("load game not found: " + name);
            yield break;
        }

#if UNITY_EDITOR
        if (SimulationSetting.IsSimulationMode)
        {
            var ret = simulator.LoadBundle(name + "lua");
            yield return(ret.WaitForDone());

            yield break;
        }
#endif

        Debug.Log("enter LoadGame " + name);

        var cfg = gamesMap[name];

        IBundleManifestLoader manifestLoader = new BundleManifestLoader();

        var path = BundleUtil.GetStorableDirectory() + name + "/";
        var mani = path + BundleSetting.ManifestFilename;

        BundleManifest  manifest       = manifestLoader.Load(mani);
        IPathInfoParser pathInfoParser = new AutoMappingPathInfoParser(manifest);
        ILoaderBuilder  builder        = new CustomBundleLoaderBuilder(new Uri(path), false);

        IBundleManager manager = new BundleManager(manifest, builder);

        var rc = new BundleResources(pathInfoParser, manager);

        cfg.resources = rc;

        var result = rc.LoadBundle(name + "lua");
        yield return(result.WaitForDone());

        cfg.luaBundle = result.Result as DefaultBundle;

        Debug.Log("leave LoadGame " + name);
    }
    public void Init(Action callback)
    {
        // 初始化 Bundle Uri 下载地址
#if UNITY_EDITOR
        DirectoryInfo dir = new DirectoryInfo(ConfigurationController.Instance.BundleUri);
        if (!dir.Exists)
        {
            LogManager.Log("Directory '{0}' does not exist.", dir.FullName);
            return;
        }
        else
        {
            LogManager.Log("初始化 Bundle Uri 下载地址 ", dir.FullName);
        }
        Uri baseUri = new Uri(dir.FullName);
        this.downloader = new WWWDownloader(baseUri, false);
#elif UNITY_IOS
        // 正式资源 Uri 从服务器获取
        // ...
#elif UNITY_ANDROID
        // 正式资源 Uri 从服务器获取
        // ...
#endif
        if (File.Exists(BundleUtil.GetStorableDirectory() + BundleSetting.ManifestFilename))
        {
            IResources _resources = CreateResources();
            context.GetContainer().Register <IResources>(_resources);
            if (callback != null)
            {
                callback.Invoke();
            }
        }
        else
        {
            StartCoroutine(_CopyManifestFromStreamingAssets(callback));
        }
    }
        protected virtual IEnumerator DoDownloadManifest(string relativePath, IProgressPromise <Progress, BundleManifest> promise)
        {
            Progress progress = new Progress();

            promise.UpdateProgress(progress);
            using (WWW www = new WWW(this.GetAbsoluteUri(relativePath)))
            {
                while (!www.isDone)
                {
                    if (www.bytesDownloaded > 0f)
                    {
                        if (progress.TotalSize <= 0)
                        {
                            progress.TotalSize = www.size;
                        }
                        progress.CompletedSize = www.bytesDownloaded;
                        promise.UpdateProgress(progress);
                    }
                    yield return(null);
                }

                progress.CompletedSize = www.bytesDownloaded;
                promise.UpdateProgress(progress);

                if (!string.IsNullOrEmpty(www.error))
                {
                    promise.SetException(new Exception(www.error));
                    yield break;
                }

                try
                {
                    byte[]         data     = www.bytes;
                    BundleManifest manifest = BundleManifest.Parse(Encoding.UTF8.GetString(data));

                    FileInfo file = new FileInfo(BundleUtil.GetStorableDirectory() + relativePath);
                    if (file.Exists)
                    {
                        FileInfo bakFile = new FileInfo(BundleUtil.GetStorableDirectory() + relativePath + ".bak");
                        if (bakFile.Exists)
                        {
                            bakFile.Delete();
                        }

                        file.CopyTo(bakFile.FullName);
                    }

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

                    File.WriteAllBytes(file.FullName, data);
                    promise.SetResult(manifest);
                }
                catch (IOException e)
                {
                    promise.SetException(e);
                }
            }
        }
    IEnumerator _CorDownload()
    {
        this.downloading = true;
        try
        {
            if (downloadProgressEvent != null)
            {
                downloadProgressEvent(0);
            }
            // 下载 Manifest
            IProgressResult <Progress, BundleManifest> manifestResult = this.downloader.DownloadManifest(BundleSetting.ManifestFilename);
            yield return(manifestResult.WaitForDone());

            if (manifestResult.Exception != null)
            {
                LogManager.Log("Downloads BundleManifest failure.Error:{0}", manifestResult.Exception);
                yield break;
            }

            // 下载 BundleInfo
            BundleManifest manifest = manifestResult.Result;
            IProgressResult <float, List <BundleInfo> > bundlesResult = this.downloader.GetDownloadList(manifest);
            yield return(bundlesResult.WaitForDone());

            List <BundleInfo> bundles = bundlesResult.Result;
            if (bundles == null || bundles.Count <= 0)
            {
                LogManager.Log("Please clear cache and remove StreamingAssets,try again.");
                yield break;
            }

            // 下载 Bundle
            IProgressResult <Progress, bool> downloadResult = this.downloader.DownloadBundles(bundles);
            downloadResult.Callbackable().OnProgressCallback(p =>
            {
                LogManager.Log("Downloading {0:F2}KB/{1:F2}KB {2:F3}KB/S", p.GetCompletedSize(UNIT.KB), p.GetTotalSize(UNIT.KB), p.GetSpeed(UNIT.KB));
                float percent = p.GetCompletedSize(UNIT.KB) / p.GetTotalSize(UNIT.KB);
                if (downloadProgressEvent != null)
                {
                    downloadProgressEvent(percent);
                }
            });
            yield return(downloadResult.WaitForDone());

            if (downloadResult.Exception != null)
            {
                LogManager.Log("Downloads AssetBundle failure.Error:{0}", downloadResult.Exception);
                yield break;
            }

            // 下载成功
            LogManager.Log(" 下载成功 ");
            IResources _resources = CreateResources();
            context.GetContainer().Unregister <IResources>();
            context.GetContainer().Register <IResources>(_resources);

#if UNITY_EDITOR
            UnityEditor.EditorUtility.OpenWithDefaultApp(BundleUtil.GetStorableDirectory());
#endif
        }
        finally
        {
            this.downloading = false;
        }
    }
示例#14
0
        public string GetFullSavePath(string relativePath)
        {
            var store = BundleUtil.GetStorableDirectory();

            return(module.Length > 0 ? (store + module + "/" + relativePath) : (store + relativePath));
        }
示例#15
0
    public IEnumerator UpdateGame(string name, Action <float> progress = null)
    {
        if (!gamesMap.ContainsKey(name))
        {
            Debug.Log("gam not found: " + name);
            yield break;
        }

        Debug.Log("enter UpdateGame " + name);
        Debug.Log("StorableDirectory: " + BundleUtil.GetStorableDirectory());

        var cfg = gamesMap[name];

        cfg.check();

        if (cfg.shouldClean)
        {
            cfg.clean();
        }

        if (!cfg.shouldUpdate)
        {
            Debug.Log("game dont need to update");
            yield break;
        }

        var path = string.Format(cfg.path, GetPlatform());

        Debug.Log("path: " + path);

        var baseUri    = new Uri(path);
        var downloader = new UnityWebRequestDownloader(baseUri, name);

        downloading = true;

        try {
            var manifestResult = downloader.DownloadManifest(BundleSetting.ManifestFilename);

            yield return(manifestResult.WaitForDone());

            if (manifestResult.Exception != null)
            {
                Debug.LogFormat("Downloads BundleManifest failure.Error:{0}", manifestResult.Exception);
                yield break;
            }

            BundleManifest manifest = manifestResult.Result;

            var bundlesResult = downloader.GetDownloadList(manifest);
            yield return(bundlesResult.WaitForDone());

            List <BundleInfo> bundles = bundlesResult.Result;

            if (bundles == null || bundles.Count <= 0)
            {
                if (progress != null)
                {
                    progress(1.0f);
                }
                //if (done != null) done(true);
                SaveVersion(name, cfg.version);
                yield break;
            }

            var downloadResult = downloader.DownloadBundles(bundles);
            downloadResult.Callbackable().OnProgressCallback(p =>
            {
                var completed = p.GetCompletedSize(UNIT.KB);
                var total     = p.GetTotalSize(UNIT.KB);
                //Debug.LogFormat("Downloading {0:F2}KB/{1:F2}KB {2:F3}KB/S", completed, total, p.GetSpeed(UNIT.KB));

                if (progress != null)
                {
                    progress((float)completed / total);
                }
            });

            yield return(downloadResult.WaitForDone());

            if (downloadResult.Exception != null)
            {
                Debug.LogFormat("Downloads AssetBundle failure.Error:{0}", downloadResult.Exception);
                //if (done != null) done(false);
                yield break;
            }

            SaveVersion(name, manifest.Version);
        }
        finally
        {
            downloading = false;
        }

        Debug.Log("leave UpdateGame " + name);
        yield break;
    }
示例#16
0
        protected virtual IEnumerator DoDownloadManifest(string relativePath, IProgressPromise <Progress, BundleManifest> promise)
        {
            Progress progress = new Progress();

            promise.UpdateProgress(progress);
            byte[] data;
            string path = this.GetAbsoluteUri(relativePath);

#if UNITY_2017_1_OR_NEWER
            using (UnityWebRequest www = new UnityWebRequest(path))
            {
                www.downloadHandler = new DownloadHandlerBuffer();
#if UNITY_2018_1_OR_NEWER
                www.SendWebRequest();
#else
                www.Send();
#endif
                while (!www.isDone)
                {
                    if (www.downloadProgress >= 0)
                    {
                        if (progress.TotalSize <= 0)
                        {
                            progress.TotalSize = (long)(www.downloadedBytes / www.downloadProgress);
                        }
                        progress.CompletedSize = (long)www.downloadedBytes;
                        promise.UpdateProgress(progress);
                    }
                    yield return(null);
                }

                if (!string.IsNullOrEmpty(www.error))
                {
                    promise.SetException(new Exception(www.error));
                    yield break;
                }

                data = www.downloadHandler.data;
            }
#else
            using (WWW www = new WWW(path))
            {
                while (!www.isDone)
                {
                    if (www.bytesDownloaded > 0f)
                    {
                        if (progress.TotalSize <= 0)
                        {
                            progress.TotalSize = (long)(www.bytesDownloaded / www.progress);
                        }
                        progress.CompletedSize = www.bytesDownloaded;
                        promise.UpdateProgress(progress);
                    }
                    yield return(null);
                }

                progress.CompletedSize = www.bytesDownloaded;
                promise.UpdateProgress(progress);

                if (!string.IsNullOrEmpty(www.error))
                {
                    promise.SetException(new Exception(www.error));
                    yield break;
                }

                data = www.bytes;
            }
#endif

            try
            {
                BundleManifest manifest = BundleManifest.Parse(Encoding.UTF8.GetString(data));

                FileInfo file = new FileInfo(BundleUtil.GetStorableDirectory() + relativePath);
                if (file.Exists)
                {
                    FileInfo bakFile = new FileInfo(BundleUtil.GetStorableDirectory() + relativePath + ".bak");
                    if (bakFile.Exists)
                    {
                        bakFile.Delete();
                    }

                    file.CopyTo(bakFile.FullName);
                }

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

                File.WriteAllBytes(file.FullName, data);
                promise.SetResult(manifest);
            }
            catch (IOException e)
            {
                promise.SetException(e);
            }
        }
示例#17
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);
        }
示例#18
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, WWW> > tasks = new List <KeyValuePair <BundleInfo, WWW> >();

            for (int i = 0; i < list.Count; i++)
            {
                BundleInfo bundleInfo = list[i];
                WWW        www        = (useCache && !bundleInfo.IsEncrypted) ? WWW.LoadFromCacheOrDownload(GetAbsoluteUri(bundleInfo.Filename), bundleInfo.Hash) : new WWW(GetAbsoluteUri(bundleInfo.Filename));
                tasks.Add(new KeyValuePair <BundleInfo, WWW>(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;
                        WWW        _www        = task.Value;

                        if (!_www.isDone)
                        {
                            tmpSize += Math.Max(0, (long)(_www.progress * _bundleInfo.FileSize));
                            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 = _www.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.bytes);
                            }
                        }
                        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);
        }