Example #1
0
        public IEnumerator GetABToLua(string _IEName, string _assetName, LuaFunction _callBack)
        {
            yield return(null);

            //获取名字(服务器的文件名字,md5处理过和原先的资源名不一样)//
            string[] _list    = _IEName.Split(split, StringSplitOptions.None);
            string   _objName = _list[_list.Length - 1];
            //去掉后缀名//
            //string _name = _assetName.Split(split, StringSplitOptions.None)[_assetName.Split(split, StringSplitOptions.None).Length - 1].Split('.')[0]; ; // _objName.Split('.')[0];
            //print("_name:" + _name);
            string _objPath = Application.persistentDataPath + "/" + _objName;
            bool   _isLocal = File.Exists(_objPath);

            if (_isLocal)
            {
            }
            else
            {
                UnityWebRequest _req = new UnityWebRequest(_IEName);
                _req.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
                _req.SendWebRequest();
                while (!_req.isDone)
                {
                    yield return(null);
                }
                File.WriteAllBytes(_objPath, _req.downloadHandler.data);
                yield return(null);

                _req.Abort();
                _req.Dispose();
            }


            //读写入的资源//
            AssetBundleCreateRequest asset = null;

            //根据路径下载对应的ab文件//
            asset = AssetBundle.LoadFromFileAsync(_objPath);
            while (!asset.isDone)
            {
                yield return(null);
            }

            Object _obj = null;

            if (asset.assetBundle != null)
            {
                //AssetBundleRequest _abReq = asset.assetBundle.LoadAllAssetsAsync();
                //int _count = 0;
                //while (!_abReq.isDone)
                //{
                //    _count++;
                //    if (_count > 20)
                //    {
                //        _count = 0;
                //        yield return null;
                //    }
                //}
                //Object[] _objList = _abReq.allAssets;

                Object[] _objList = asset.assetBundle.LoadAllAssets();

                if (_objList != null)
                {
                    if (_callBack != null)
                    {
                        _callBack.Call(_objList);
                    }
                }
                if (asset != null && asset.assetBundle != null)
                {
                    asset.assetBundle.Unload(false);
                }
                yield return(null);

                asset = null;
            }

            yield return(null);
        }
    //-------------------------------------------------------------------------------------------------------------------------------------
    protected IEnumerator loadAssetBundleCoroutine(AssetBundleInfo bundleInfo)
    {
        ++mAssetBundleCoroutineCount;
        // 先确保依赖项全部已经加载完成,才能开始加载当前请求的资源包
        while (!bundleInfo.isAllParentLoaded())
        {
            bundleInfo.loadParentAsync();
            yield return(null);
        }
        logInfo(bundleInfo.getBundleFileName() + " start load bundle", LOG_LEVEL.LL_NORMAL);
        bundleInfo.setLoadState(LOAD_STATE.LS_LOADING);
        AssetBundle assetBundle = null;

        // 加载远端文件时使用www
        if (!ResourceManager.mLocalRootPath)
        {
            if (ResourceManager.mPersistentFirst)
            {
                string path = CommonDefine.F_PERSISTENT_DATA_PATH + bundleInfo.getBundleFileName();
                checkDownloadPath(ref path, ResourceManager.mLocalRootPath);
                WWW www = new WWW(path);
                yield return(www);

                if (www.error == null)
                {
                    assetBundle = www.assetBundle;
                }
                www.Dispose();
            }
            if (assetBundle == null)
            {
                string path = ResourceManager.mResourceRootPath + bundleInfo.getBundleFileName();
                checkDownloadPath(ref path, ResourceManager.mLocalRootPath);
                WWW www = new WWW(path);
                yield return(www);

                if (www.error == null)
                {
                    assetBundle = www.assetBundle;
                }
                www.Dispose();
            }
        }
        // 直接从文件加载,只能加载本地文件
        else
        {
            AssetBundleCreateRequest request = null;
            string path = CommonDefine.F_PERSISTENT_DATA_PATH + bundleInfo.getBundleFileName();
            if (ResourceManager.mPersistentFirst && isFileExist(path))
            {
                request = AssetBundle.LoadFromFileAsync(path);
            }
            if (request == null)
            {
                path = ResourceManager.mResourceRootPath + bundleInfo.getBundleFileName();
                if (isFileExist(path))
                {
                    request = AssetBundle.LoadFromFileAsync(path);
                }
            }
            if (request != null)
            {
                yield return(request);

                assetBundle = request.assetBundle;
            }
            else
            {
                logError("can not load asset bundle async : " + bundleInfo.getBundleFileName());
                --mAssetBundleCoroutineCount;
            }
        }
        logInfo(bundleInfo.getBundleFileName() + " load bundle done", LOG_LEVEL.LL_NORMAL);
        yield return(new WaitForEndOfFrame());

        // 通知AssetBundleInfo
        bundleInfo.notifyAssetBundleAsyncLoadedDone(assetBundle);
        --mAssetBundleCoroutineCount;
    }
 private IEnumerator Loader(AssetBundleCreateRequest request)
 {
     yield return(request);
 }
Example #4
0
    IEnumerator LoadResPackageAsynEnumerator(string PackName, IResourceLoad iLoad)
    {
        if (RequestTable.Contains(PackName))
        {
            RequestPackageInfo info = RequestTable[PackName] as RequestPackageInfo;
            if (info.bLoading == true)
            {
                yield break;
            }
        }

        Resources.UnloadUnusedAssets();
        Caching.CleanCache();

        ResLoadResult ret = new ResLoadResult();

        ret.fProgress = 1.0f;
        ret.resObj    = null;
        ret.sErrorMsg = "";
        ret.sPath     = PackName;

        if (RequestTable.Contains(PackName))
        {
            RequestPackageInfo info = RequestTable[PackName] as RequestPackageInfo;
            info.bLoading          = true;
            RequestTable[PackName] = info;
        }

        long   t1         = Api.GetTickCount();
        string ext        = bEncrypt ? ".zen" : ".unity3D";
        string outerpath  = ResDef.OuterPackageDirectory + PackName + ext;
        string innerpath1 = ResDef.InterPackageDirectoryEx + PackName + ext;
        string innerpath2 = ResDef.InterPackageDirectory + PackName + ext;

        string finalpath = "";
        WWW    www       = null;
        AssetBundleCreateRequest request = null;

        //外包优先
        if (System.IO.File.Exists(outerpath))
        {
            finalpath = outerpath;
            //if (!bEncrypt &&(Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)) //对于外包,如果没加密则直接采用读文件方式
            if (false)
            {
                byte[] data = System.IO.File.ReadAllBytes(outerpath);
                if (data != null)
                {
                    request = AssetBundle.LoadFromMemoryAsync(data);
                    while (!request.isDone)
                    {
                        yield return(new WaitForEndOfFrame());
                    }
                }
                data = null;
                System.GC.Collect();
                yield return(new WaitForEndOfFrame());
            }
            else
            {
                www = WWW.LoadFromCacheOrDownload("file:///" + outerpath, 5);
                //www = new WWW("file:///" + outerpath);
                yield return(www);
            }
        }
        //内包由于有可能在jar/zip等压缩包内,只能通过www组件去提取
        else if (System.IO.File.Exists(innerpath1))
        {
            finalpath = innerpath1;
            www       = new WWW("file:///" + innerpath1);
            yield return(www);
        }
        else
        {
            finalpath = innerpath2;
            yield return(true);
        }

        if (RequestTable.Contains(PackName))
        {
            RequestPackageInfo info = RequestTable[PackName] as RequestPackageInfo;
            info.bLoading          = false;
            RequestTable[PackName] = info;
        }

        AssetBundle pAssetBundle = null;

        if (www != null)
        {
            if (www.error == null)
            {
                if (!CachePackages.Contains(PackName))
                {
                    try
                    {
                        if (bEncrypt)
                        {
                            string key     = PackName + "*^$@&%#!";
                            byte[] outdata = DecryptDES(www.bytes, key);
                            if (outdata != null)
                            {
#if U462
                                pAssetBundle = AssetBundle.LoadFromMemory(outdata);
#else
                                string temppath = ResDef.UserPath + "temp.unity3d";
                                System.IO.File.WriteAllBytes(temppath, outdata);
                                pAssetBundle = AssetBundle.CreateFromFile(temppath);
#endif
                            }
                        }
                        else
                        {
                            pAssetBundle = www.assetBundle;
                        }
                    }
                    catch (UnityException e)
                    {
                        Trace.LogError(e.ToString());
                    }
                    if (pAssetBundle != null)
                    {
                        CachePackages[PackName] = pAssetBundle;
                        CacheOrders.Add(PackName);
                        long t2 = Api.GetTickCount();
                        long dt = t2 - t1;
                        Trace.Log("LoadResPackageAsynEnumerator OK, www.assetBundle OK:" + finalpath + ",time=" + dt.ToString() + "ms");
                    }
                    else
                    {
                        Trace.LogError("LoadResPackageAsynEnumerator fail, www.assetBundle fail:" + finalpath);
                    }
                }
            }
            else
            {
                Trace.LogError("LoadResPackageAsynEnumerator fail, www.errpr fail:" + www.error);
            }

            www.Dispose();
            www = null;
        }
        else if (request != null)
        {
            if (request.isDone)
            {
                if (!CachePackages.Contains(PackName))
                {
                    try
                    {
                        pAssetBundle = request.assetBundle;
                    }
                    catch (UnityException e)
                    {
                        Trace.LogError(e.ToString());
                    }
                    if (pAssetBundle != null)
                    {
                        CachePackages[PackName] = pAssetBundle;
                        CacheOrders.Add(PackName);
                        long t2 = Api.GetTickCount();
                        long dt = t2 - t1;
                        Trace.Log("LoadResPackageAsynEnumerator OK, www.assetBundle OK:" + finalpath + ",time=" + dt.ToString() + "ms");
                    }
                    else
                    {
                        Trace.LogError("LoadResPackageAsynEnumerator fail, www.assetBundle fail:" + finalpath);
                    }
                }
            }
            else
            {
                Trace.LogError("LoadResPackageAsynEnumerator fail, www.errpr fail:" + www.error);
            }
            request = null;
        }
        else
        {
            Trace.LogError("LoadResPackageAsynEnumerator fail, www null,package doesn't exists:" + finalpath);
        }

        System.GC.Collect();
        yield return(new WaitForEndOfFrame());

        InvokePackageCallback(ret, PackName, iLoad);
    }
Example #5
0
        IEnumerator DownloadAssetBundle()
        {
            // Create and send our request
            request = new HTTPRequest(new Uri(this.sampleSelector.BaseURL + this._path)).Send();

            this._statusText.text = "Download started";

            // Wait while it's finishes and add some fancy dots to display something while the user waits for it.
            // A simple "yield return StartCoroutine(request);" would do the job too.
            while (request.State < HTTPRequestStates.Finished)
            {
                yield return(new WaitForSeconds(0.1f));

                this._statusText.text += ".";
            }

            // Check the outcome of our request.
            switch (request.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:

                if (request.Response.IsSuccess)
                {
#if !BESTHTTP_DISABLE_CACHING
                    if (request.Response.IsFromCache)
                    {
                        this._statusText.text = "Loaded from local cache!";
                    }
                    else
                    {
                        this._statusText.text = "Downloaded!";
                    }
#else
                    this._statusText.text = "Downloaded!";
#endif

                    // Start creating the downloaded asset bundle
                    AssetBundleCreateRequest async =
#if UNITY_5_3_OR_NEWER
                        AssetBundle.LoadFromMemoryAsync(request.Response.Data);
#else
                        AssetBundle.CreateFromMemory(request.Response.Data);
#endif

                    // wait for it
                    yield return(async);

                    BestHTTP.PlatformSupport.Memory.BufferPool.Release(request.Response.Data);

                    // And process the bundle
                    yield return(StartCoroutine(ProcessAssetBundle(async.assetBundle)));
                }
                else
                {
                    this._statusText.text = string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                                          request.Response.StatusCode,
                                                          request.Response.Message,
                                                          request.Response.DataAsText);
                    Debug.LogWarning(this._statusText.text);
                }

                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                this._statusText.text = "Request Finished with Error! " + (request.Exception != null ? (request.Exception.Message + "\n" + request.Exception.StackTrace) : "No Exception");
                Debug.LogError(this._statusText.text);
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                this._statusText.text = "Request Aborted!";
                Debug.LogWarning(this._statusText.text);
                break;

            // Connecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                this._statusText.text = "Connection Timed Out!";
                Debug.LogError(this._statusText.text);
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                this._statusText.text = "Processing the request Timed Out!";
                Debug.LogError(this._statusText.text);
                break;
            }

            this._downloadButton.enabled = true;
        }
    private IEnumerator _LoadAssetBundleAsync(AssetBundleInfo bundleInfo, bool loadDependence = true)
    {
        while (bundleInfo.isLoading)
        {
            yield return(null);
        }

        if (bundleInfo.isDone)
        {
            yield break;
        }

        Debug.LogFormat("AssetBundleManager._LoadAssetBundleAsync {0}", bundleInfo.url);

        bundleInfo.isLoading = true;
        if (loadDependence)
        {
            yield return(CoroutineHelper.Run(_LoadDependenciesAsync(bundleInfo.pack)));
        }

        string bundleName  = bundleInfo.pack.name;
        string bundleNameV = bundleName;// + "." + bundleInfo.pack.checksum;
        string loadpath    = null;

#if !USE_BUNDLE_IN_EDITOR && (UNITY_EDITOR || UNITY_STANDALONE || !PUBLISH || ENABLE_GM)
        string search_path  = System.IO.Path.Combine(Application.persistentDataPath, bundleNameV);
        string search_path2 = System.IO.Path.Combine(Defines.LuaFileSearchPath[2], bundleNameV);
        if (System.IO.File.Exists(search_path))
        {
            loadpath = search_path;
            Debug.LogFormat("AssetBundleManager._LoadAssetBundleAsync search_path {0}", search_path);
        }
        else if (System.IO.File.Exists(search_path2))
        {
            loadpath = search_path2;
            Debug.LogFormat("AssetBundleManager._LoadAssetBundleAsync search_path {0}", search_path);
        }
#endif
        if (loadpath == null)
        {
            loadpath = bundleInfo.url;
        }
        AssetBundleCreateRequest loader = AssetBundle.LoadFromFileAsync(loadpath);
        yield return(loader);

        if (bundleInfo.isDone) // loaded by sync method
        {
            if (loader.isDone && loader.assetBundle != null)
            {
                loader.assetBundle.Unload(false);
            }
            yield break;
        }

        if (!loader.isDone)
        {
            bundleInfo.isLoading = false;
            Debug.LogErrorFormat("AssetBundleManager.LoadAssetBundleAsync can't async load bundle: {0} reason: {1}", bundleName, "NOT FOUND!");
        }
        else
        {
            bundleInfo.isLoading = false;
            if (loader.assetBundle != null)
            {
                bundleInfo.bundle = loader.assetBundle;
                bundleInfo.isDone = true;
                Debug.LogFormat("AssetBundleManager.LoadAssetBundleAsync async load done bundle: {0}", bundleName);
            }
            else
            {
                Debug.LogErrorFormat("AssetBundleManager.LoadAssetBundleAsync can't async load bundle: {0}", bundleName);
            }
        }
    }
Example #7
0
        public void BeginLoad(CRequest req)
        {
            this.isFree  = false;
            this._req    = req;
            this.enabled = true;
            string url = req.url;

#if HUGULA_WEB_MODE
            if (req.isAssetBundle)
            {
                url = req.uris.OnOverrideUrl(req);
            }
#endif
            url = CUtils.CheckWWWUrl(url);

#if HUGULA_LOADER_DEBUG
            Debug.LogFormat(" 1.0 <color=#15C1B2> begin load : url({0}),key:({1}) assetName({2}) abName({3}) isNativeFile({4}) isAssetBundle({5}) frame{6} )</color>", url, req.key, req.assetName, req.assetBundleName, req.isNativeFile, req.isAssetBundle, Time.frameCount);
#endif
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2
            if (req.isAssetBundle && req.isLoadFromCacheOrDownload)
#else
            if (req.isNativeFile && req.isAssetBundle && !req.isLoadFromCacheOrDownload)
            {
                /*
                 * Stream Compressed (LZMA) Mem: LZ4 compressed bundle size.  Perf: reading from disk + LZMA decompression + LZ4 compression.
                 * Chunk Compressed (LZ4)   Mem: no extra memory is used.     Perf: reading from disk.
                 */
                #if UNITY_ANDROID && !UNITY_EDITOR
                string android_url = req.url;
                android_url = android_url.Replace(Common.JAR_FILE, "").Replace("!/assets", "!assets");
                abRequest   = AssetBundle.LoadFromFileAsync(android_url);
                // Debug.LogFormat("android_url={0},url={1}",android_url,req.url);
                #else
                abRequest = AssetBundle.LoadFromFileAsync(req.url);
                #endif
            }
            else if (req.isAssetBundle && req.isLoadFromCacheOrDownload)
#endif
            {
                if (CResLoader.assetBundleManifest != null)
                {
                    www = WWW.LoadFromCacheOrDownload(url, CResLoader.assetBundleManifest.GetAssetBundleHash(req.assetBundleName), 0);
                }
                else
                {
                    www = WWW.LoadFromCacheOrDownload(url, 0);
                }
            }
            else if (req.head is WWWForm)
            {
                www = new WWW(url, (WWWForm)req.head);
            }
            else if (req.head is System.Array)
            {
                www = new WWW(url, (byte[])req.head);
            }
            else if (req.head is string)
            {
                www = new WWW(url, LuaHelper.GetBytes(req.head.ToString()));
            }
            else
            {
                www = new WWW(url);
            }

            if (www != null)
            {
                if (req.priority > 10000)
                {
                    www.threadPriority = ThreadPriority.High;
                }
                else if (req.priority < -10000)
                {
                    www.threadPriority = ThreadPriority.Low;
                }
                else if (req.priority < 0)
                {
                    www.threadPriority = ThreadPriority.BelowNormal;
                }
            }
            if (abRequest != null)
            {
                abRequest.priority = req.priority;
            }
        }
 public static void AddAsset(AssetStoreAsset searchResult, Texture2D placeholderPreviewImage)
 {
     if (placeholderPreviewImage != null)
     {
         searchResult.previewImage = AssetStoreAssetSelection.ScaleImage(placeholderPreviewImage, 256, 256);
     }
     searchResult.previewInfo          = null;
     searchResult.previewBundleRequest = null;
     if (!string.IsNullOrEmpty(searchResult.dynamicPreviewURL) && searchResult.previewBundle == null)
     {
         searchResult.disposed = false;
         AsyncHTTPClient client = new AsyncHTTPClient(searchResult.dynamicPreviewURL);
         client.doneCallback = delegate(AsyncHTTPClient c)
         {
             if (!client.IsSuccess())
             {
                 Console.WriteLine("Error downloading dynamic preview: " + client.text);
                 searchResult.dynamicPreviewURL = null;
                 AssetStoreAssetSelection.DownloadStaticPreview(searchResult);
                 return;
             }
             AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset();
             if (searchResult.disposed || firstAsset == null || searchResult.id != firstAsset.id)
             {
                 return;
             }
             try
             {
                 AssetBundleCreateRequest cr = AssetBundle.LoadFromMemoryAsync(c.bytes);
                 cr.DisableCompatibilityChecks();
                 searchResult.previewBundleRequest = cr;
                 EditorApplication.CallbackFunction callback = null;
                 double startTime = EditorApplication.timeSinceStartup;
                 callback = delegate
                 {
                     AssetStoreUtils.UpdatePreloading();
                     if (!cr.isDone)
                     {
                         double timeSinceStartup = EditorApplication.timeSinceStartup;
                         if (timeSinceStartup - startTime > 10.0)
                         {
                             EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, callback);
                             Console.WriteLine("Timed out fetch live preview bundle " + (searchResult.dynamicPreviewURL ?? "<n/a>"));
                         }
                         return;
                     }
                     EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, callback);
                     AssetStoreAsset firstAsset2 = AssetStoreAssetSelection.GetFirstAsset();
                     if (!searchResult.disposed && firstAsset2 != null && searchResult.id == firstAsset2.id)
                     {
                         searchResult.previewBundle = cr.assetBundle;
                         if (cr.assetBundle == null || cr.assetBundle.mainAsset == null)
                         {
                             searchResult.dynamicPreviewURL = null;
                             AssetStoreAssetSelection.DownloadStaticPreview(searchResult);
                         }
                         else
                         {
                             searchResult.previewAsset = searchResult.previewBundle.mainAsset;
                         }
                     }
                 };
                 EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, callback);
             }
             catch (Exception ex)
             {
                 Console.Write(ex.Message);
                 Debug.Log(ex.Message);
             }
         };
         client.Begin();
     }
     else if (!string.IsNullOrEmpty(searchResult.staticPreviewURL))
     {
         AssetStoreAssetSelection.DownloadStaticPreview(searchResult);
     }
     AssetStoreAssetSelection.AddAssetInternal(searchResult);
     AssetStoreAssetSelection.RefreshFromServer(null);
 }
        public override void Update()
        {
            // 如果资源文件加载完毕
            if (States == ELoaderStates.Success || States == ELoaderStates.Fail)
            {
                UpdateAllProvider();
                return;
            }

            if (States == ELoaderStates.None)
            {
                States = ELoaderStates.LoadDepends;
            }

            // 1. 加载所有依赖项
            if (States == ELoaderStates.LoadDepends)
            {
                string[] dependencies = AssetSystem.BundleServices.GetDirectDependencies(_manifestPath);
                if (dependencies.Length > 0)
                {
                    foreach (string dpManifestPath in dependencies)
                    {
                        string          dpLoadPath = AssetSystem.BundleServices.GetAssetBundleLoadPath(dpManifestPath);
                        AssetLoaderBase dpLoader   = AssetSystem.CreateLoaderInternal(dpLoadPath, dpManifestPath);
                        _depends.Add(dpLoader);
                    }
                }
                States = ELoaderStates.CheckDepends;
            }

            // 2. 检测所有依赖完成状态
            if (States == ELoaderStates.CheckDepends)
            {
                foreach (var dpLoader in _depends)
                {
                    if (dpLoader.IsDone() == false)
                    {
                        return;
                    }
                }
                States = ELoaderStates.LoadFile;
            }

            // 3. 加载AssetBundle
            if (States == ELoaderStates.LoadFile)
            {
#if UNITY_EDITOR
                // 注意:Unity2017.4编辑器模式下,如果AssetBundle文件不存在会导致编辑器崩溃,这里做了预判。
                if (System.IO.File.Exists(LoadPath) == false)
                {
                    MotionLog.Warning($"Not found assetBundle file : {LoadPath}");
                    States = ELoaderStates.Fail;
                    return;
                }
#endif

                // Load assetBundle file
                if (AssetSystem.DecryptServices != null)
                {
                    if (AssetSystem.DecryptServices.DecryptType == EDecryptMethod.GetDecryptOffset)
                    {
                        ulong offset = AssetSystem.DecryptServices.GetDecryptOffset(LoadPath);
                        _cacheRequest = AssetBundle.LoadFromFileAsync(LoadPath, 0, offset);
                    }
                    else if (AssetSystem.DecryptServices.DecryptType == EDecryptMethod.GetDecryptBinary)
                    {
                        byte[] binary = AssetSystem.DecryptServices.GetDecryptBinary(LoadPath);
                        _cacheRequest = AssetBundle.LoadFromMemoryAsync(binary);
                    }
                    else
                    {
                        throw new NotImplementedException($"{AssetSystem.DecryptServices.DecryptType}");
                    }
                }
                else
                {
                    _cacheRequest = AssetBundle.LoadFromFileAsync(LoadPath);
                }
                States = ELoaderStates.CheckFile;
            }

            // 4. 检测AssetBundle加载结果
            if (States == ELoaderStates.CheckFile)
            {
                if (_cacheRequest.isDone == false)
                {
                    return;
                }
                CacheBundle = _cacheRequest.assetBundle;

                // Check error
                if (CacheBundle == null)
                {
                    MotionLog.Warning($"Failed to load assetBundle file : {LoadPath}");
                    States = ELoaderStates.Fail;
                }
                else
                {
                    States = ELoaderStates.Success;
                }
            }
        }
        private IEnumerator InitUI()
        {
            PopupRoomInstance[] pris;
            while ((pris = Resources.FindObjectsOfTypeAll <PopupRoomInstance>()).Length == 0)
            {
                yield return(null);
            }

            PopupRoomInstance pri = pris[0];

            RectTransform nameTextRT = pri.transform.Find("Popup/NameText").GetComponent <RectTransform>();

            nameTextRT.GetComponent <Text>().alignment = TextAnchor.MiddleLeft;



            byte[] data = Properties.Resources.dropdown;
            AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(data);

            while (!request.isDone)
            {
                yield return(null);
            }
            if (request.assetBundle == null)
            {
                MelonModLogger.LogError("Unable to load dropdown Assetbundle");
                yield break;
            }

            //Load main prefab
            AssetBundleRequest abrMain = request.assetBundle.LoadAssetWithSubAssetsAsync("Assets/Prefabs/Dropdown.prefab");

            while (!abrMain.isDone)
            {
                yield return(null);
            }
            if (abrMain.asset == null)
            {
                MelonModLogger.LogError("Unable to load Dropdown prefab from Assetbundle (prefab is null)");
                yield break;
            }
            Dropdown prefab = abrMain.asset.Cast <GameObject>().GetComponent <Dropdown>();

            if (prefab == null)
            {
                MelonModLogger.LogError("Invalid Dropdown prefab: Missing Dropdown script");
                yield break;
            }

            Log("Dropdown prefab is valid");

            serverDropdown = GameObject.Instantiate(prefab, pri.GetComponent <RectTransform>());
            RectTransform ddRT = serverDropdown.GetComponent <RectTransform>();

            ddRT.localPosition += new Vector3(250, 150);
            ddRT.sizeDelta     += new Vector2(200, 0);

            defaultServer.appVersion = GameObject.FindObjectOfType <VRCApplicationSetup>().Method_Public_String_2();

            serverList = new List <ServerDef> {
                defaultServer, ServerDef.DedicatedServer("Slaynash EUW Server", "31.204.91.102", 5055)                               /*, ServerDef.DedicatedServer("Local Server", "127.0.0.1", 5055)*/
            };
            serverDropdown.ClearOptions();
            Il2CppSystem.Collections.Generic.List <string> options = new Il2CppSystem.Collections.Generic.List <string>(serverList.Count);
            foreach (ServerDef serverdef in serverList)
            {
                options.Add(serverdef.name);
            }
            serverDropdown.AddOptions(options);
        }
 public ETTask <AssetBundle> LoadAsync(string path)
 {
     this.tcs     = new ETTaskCompletionSource <AssetBundle>();
     this.request = AssetBundle.LoadFromFileAsync(path);
     return(this.tcs.Task);
 }
 public FileLoadAssetBundleRequest(string path, AssetBundleInfo info) : base(info)
 {
     createRequest = AssetBundle.LoadFromFileAsync(path);
 }
Example #13
0
        private void OnCompletedCallback(AsyncOperation obj)
        {
            AssetBundleCreateRequest request = obj as AssetBundleCreateRequest;

            m_AssetBundle = request.assetBundle;
        }
Example #14
0
 public void Play(AssetBundleCreateRequest ab)
 {
     playing = true;
     abcr    = ab;
 }
Example #15
0
 public Task <AssetBundle> LoadAsync(string bundleName)
 {
     this.tcs     = new TaskCompletionSource <AssetBundle>();
     this.request = AssetBundle.LoadFromFileAsync(Path.Combine(PathHelper.AppHotfixResPath, bundleName));
     return(this.tcs.Task);
 }
Example #16
0
 public void Dispose()
 {
     this.creatRequest = null;
     this.tcc          = null;
 }
 public void Initialize()
 {
     AssetBundle.UnloadAllAssetBundles(true);
     _asyncOperation = AssetBundle.LoadFromFileAsync("Assets/UnityCoreSystems/Systems/Tests/Promises/Playmode/ModuleTests/AsyncOperationAwaitSupportTests/Resources/test.bundle");
 }
Example #18
0
        /// <summary>
        ///  加载
        /// 一般来说,主资源才需要load
        /// 依赖资源只要加载ab,会自动依赖
        /// </summary>
        /// <param name="assetHash"></param>
        /// <param name="isLoadObj">是否需要返回加载资源</param>
        /// <param name="callback"></param>
        /// <returns></returns>
        IEnumerator IEAsyncLoadAssetbundle(string assetHash, bool isLoadObj, Action <LoadAssetState, Object> callback)
        {
            //
            var mainItem = config.Manifest.GetManifestItemByHash(assetHash);

            //单ab 多资源,加载真正ab名
            if (mainItem != null && !string.IsNullOrEmpty(mainItem.Package))
            {
                assetHash = mainItem.Package;
            }

            //正在被加载中,放入后置队列
            if (lockSet.Contains(assetHash))
            {
                callback(LoadAssetState.IsLoding, null);
                yield break;
            }

            //没被加载
            if (!AssetbundleMap.ContainsKey(assetHash))
            {
                AssetBundleCreateRequest ret = null;
                string fullpath = "";
                //加锁
                lockSet.Add(assetHash);
                {
                    fullpath = FindAsset(assetHash);
                    ret      = AssetBundle.LoadFromFileAsync(fullpath);
                    yield return(ret);
                }
                //解锁
                lockSet.Remove(assetHash);
                //添加assetbundle
                if (ret.assetBundle != null)
                {
                    AddAssetBundle(assetHash, ret.assetBundle);
                    if (isLoadObj)
                    {
                        callback(LoadAssetState.Success, LoadFormAssetBundle <Object>(assetHash));
                    }
                    else
                    {
                        callback(LoadAssetState.Success, null);
                    }
                }
                else
                {
                    callback(LoadAssetState.Fail, null);
                    BDebug.LogError("ab资源为空:" + fullpath);
                }
            }
            else
            {
                if (isLoadObj)
                {
                    callback(LoadAssetState.Success, LoadFormAssetBundle <Object>(assetHash));
                }
                else
                {
                    callback(LoadAssetState.Success, null);
                }
            }
        }
Example #19
0
 internal override void Unload()
 {
     _request  = null;
     loadState = LoadState.Unload;
     base.Unload();
 }
Example #20
0
        private System.Collections.IEnumerator LoadFileCoroutine()
        {
            if (startHandler != null)
            {
                startHandler(this);
            }
            string    localPath;
            AssetInfo localAssetInfo;
            AssetInfo remoteAssetInfo;

            if (ResMgr.instance.localManifest.assetDic.TryGetValue(_resObj.SubPath, out localAssetInfo) &&
                ResMgr.instance.remoteManifest.assetDic.TryGetValue(_resObj.SubPath, out remoteAssetInfo) &&
                localAssetInfo.Equals(remoteAssetInfo) && ResUtil.ExistsInLocal(_resObj.SubPath + _resObj.Suffix, out localPath))
            {
                _formLocal = true;
                byte[] bytes = System.IO.File.ReadAllBytes(localPath);
                if (bytes == null)
                {
                    if (errorHandler != null)
                    {
                        errorHandler(this);
                    }
                    Debugger.LogError(string.Format("{0}读取ab文件失败,可能本地文件已损坏", _resObj));
                    UnityEngine.Object.Destroy(this);
                }
                AssetBundleCreateRequest abcr = AssetBundle.CreateFromMemory(bytes);
                while (!abcr.isDone)
                {
                    if (_state == EResLoaderState.Error)
                    {
                        break;
                    }
                    CurrentProgress = abcr.progress;
                    yield return(null);
                }
                if (_state == EResLoaderState.Error)
                {
                    abcr = null;

                    if (_resObj.MaxTryLoadNum > 0 && _reLoadNum > _resObj.MaxTryLoadNum)
                    {
                        if (errorHandler != null)
                        {
                            errorHandler(this);
                        }
                        Debugger.LogError(string.Format("{0}加载失败…{1}次尝试加载,可能本地文件已损坏", _resObj, _reLoadNum));
                        //#if !UNITY_EDITOR
                        UnityEngine.Object.Destroy(this);
                        //#endif
                    }
                    else
                    {
                        Debugger.LogError(string.Format("{0}加载本地文件失败,可能本地文件已损坏,直接删除本地文件,重新下载", _resObj));
                        System.IO.File.Delete(localPath);
                        yield return(new WaitForSeconds(1f));

                        _state = EResLoaderState.READY;
                        Load();
                    }
                }
                else
                {
                    //_assetBundle = abcr.assetBundle;
                    //if (_assetBundle == null)
                    //    Debugger.LogError("you must load assetBundle file with resloader" + _resObj);
                    _state          = EResLoaderState.Complete;
                    CurrentProgress = 1f;
                    if (completeHandler != null)
                    {
                        completeHandler(this);
                    }
                    //#if !UNITY_EDITOR
                    UnityEngine.Object.Destroy(this);
                    //#endif
                }
            }
            else
            {
                WWW www = new WWW(ResUtil.GetRemotePath(_resObj.SubPath + _resObj.Suffix) + Logic.Game.GameConfig.instance.param);
                Debugger.Log(www.url);
                www.threadPriority = ThreadPriority.High;
                while (!www.isDone)
                {
                    if (_state == EResLoaderState.Error)
                    {
                        break;
                    }
                    CurrentProgress = www.progress;
                    yield return(null);
                }
                if (!string.IsNullOrEmpty(www.error))
                {
                    _state = EResLoaderState.Error;
                }
                if (_state == EResLoaderState.Error)
                {
                    Debugger.LogError(string.Format("{0}加载失败", www.url));
                    www.Dispose();
                    www = null;
                    if (_resObj.MaxTryLoadNum > 0 && _reLoadNum > _resObj.MaxTryLoadNum)
                    {
                        if (errorHandler != null)
                        {
                            errorHandler(this);
                        }
                        //#if !UNITY_EDITOR
                        UnityEngine.Object.Destroy(this);
                        //#endif
                    }
                    else
                    {
                        Debugger.LogError(string.Format("{0}加载失败…第{1}次尝试加载", _resObj, _reLoadNum));
                        yield return(new WaitForSeconds(1f));

                        _state = EResLoaderState.READY;
                        Load();
                    }
                }
                else
                {
                    ResUtil.Save2Local(_resObj.SubPath + _resObj.Suffix, www.bytes);

                    if (ResMgr.instance.remoteManifest.assetDic.TryGetValue(_resObj.SubPath, out remoteAssetInfo))
                    {
                        ResMgr.instance.localManifest.assetDic[_resObj.SubPath] = remoteAssetInfo;
                        ResUtil.SaveManifest2Local(ResMgr.instance.localManifest);//同步远程和本地的manifest
                    }
                    _state = EResLoaderState.Complete;
                    //_assetBundle = www.assetBundle;
                    www.Dispose();
                    www = null;
                    //if (_assetBundle == null)
                    //    Debugger.LogError("you must load assetBundle file with resloader");
                    //if(_resObj)
                    //_assetBundle.Unload(true);
                    CurrentProgress = 1f;
                    if (completeHandler != null)
                    {
                        completeHandler(this);
                    }
                    //#if !UNITY_EDITOR
                    UnityEngine.Object.Destroy(this);
                    //#endif
                }
            }
        }
 public AssetBundleLoadDecrypted(byte[] decryptedData, string assetBundleName) : base(assetBundleName)
 {
     m_Operation = AssetBundle.LoadFromMemoryAsync(decryptedData);
 }
Example #22
0
        public void Update()
        {
            //@TODO: Try to overlap Resources load and entities scene load

            // Begin Async resource load
            if (_LoadingStatus == LoadingStatus.NotStarted)
            {
                if (_SceneSize == 0)
                {
                    return;
                }

                try
                {
                    _StartTime = Time.realtimeSinceStartup;

                    if (_ExpectedObjectReferenceCount != 0)
                    {
#if UNITY_EDITOR
                        if (!_UsingBundles)
                        {
                            var resourceRequests = UnityEditorInternal.InternalEditorUtility.LoadSerializedFileAndForget(_ResourcesPathObjRefs);
                            _ResourceObjRefs = (ReferencedUnityObjects)resourceRequests[0];

                            _LoadingStatus = LoadingStatus.WaitingForResourcesLoad;
                        }
                        else
#endif
                        {
                            _AssetBundleRequest = AssetBundle.LoadFromFileAsync(_ResourcesPathObjRefs);
                            _LoadingStatus      = LoadingStatus.WaitingForAssetBundleLoad;
                        }
                    }
                    else
                    {
                        _LoadingStatus = LoadingStatus.WaitingForEntitiesLoad;
                    }

                    if (!_UsingBundles)
                    {
                        _FileContent = (byte *)UnsafeUtility.Malloc(_SceneSize, 16, Allocator.Persistent);

                        ReadCommand cmd;
                        cmd.Buffer  = _FileContent;
                        cmd.Offset  = 0;
                        cmd.Size    = _SceneSize;
                        _ReadHandle = AsyncReadManager.Read(_ScenePath, &cmd, 1);
                    }
                }
                catch (Exception e)
                {
                    _LoadingFailure = e.Message;
                    _LoadingStatus  = LoadingStatus.Completed;
                }
            }

            // Once async asset bundle load is done, we can read the asset
            if (_LoadingStatus == LoadingStatus.WaitingForAssetBundleLoad)
            {
                if (!_AssetBundleRequest.isDone)
                {
                    return;
                }

                if (!_AssetBundleRequest.assetBundle)
                {
                    _LoadingFailure = $"Failed to load Asset Bundle '{_ResourcesPathObjRefs}'";
                    _LoadingStatus  = LoadingStatus.Completed;
                    return;
                }
                _AssetBundle = _AssetBundleRequest.assetBundle;

                _AssetRequest  = _AssetBundle.LoadAssetAsync(Path.GetFileName(_ResourcesPathObjRefs));
                _LoadingStatus = LoadingStatus.WaitingForAssetLoad;

                _FileContent = (byte *)UnsafeUtility.Malloc(_SceneSize, 16, Allocator.Persistent);

                ReadCommand cmd;
                cmd.Buffer  = _FileContent;
                cmd.Offset  = 0;
                cmd.Size    = _SceneSize;
                _ReadHandle = AsyncReadManager.Read(_ScenePath, &cmd, 1);
            }

            // Once async asset bundle load is done, we can read the asset
            if (_LoadingStatus == LoadingStatus.WaitingForAssetLoad)
            {
                if (!_AssetRequest.isDone)
                {
                    return;
                }

                if (!_AssetRequest.asset)
                {
                    _LoadingFailure = $"Failed to load Asset '{Path.GetFileName(_ResourcesPathObjRefs)}'";
                    _LoadingStatus  = LoadingStatus.Completed;
                    return;
                }

                _ResourceObjRefs = _AssetRequest.asset as ReferencedUnityObjects;

                if (_ResourceObjRefs == null)
                {
                    _LoadingFailure = $"Failed to load object references resource '{_ResourcesPathObjRefs}'";
                    _LoadingStatus  = LoadingStatus.Completed;
                    return;
                }
                _LoadingStatus = LoadingStatus.WaitingForEntitiesLoad;
            }

            // Once async resource load is done, we can async read the entity scene data
            if (_LoadingStatus == LoadingStatus.WaitingForResourcesLoad)
            {
                if (_ResourceObjRefs == null)
                {
                    _LoadingFailure = $"Failed to load object references resource '{_ResourcesPathObjRefs}'";
                    _LoadingStatus  = LoadingStatus.Completed;
                    return;
                }

                _LoadingStatus = LoadingStatus.WaitingForEntitiesLoad;
            }

            if (_LoadingStatus == LoadingStatus.WaitingForEntitiesLoad)
            {
                try
                {
                    _LoadingStatus = LoadingStatus.WaitingForSceneDeserialization;
                    ScheduleSceneRead(_ResourceObjRefs);
                }
                catch (Exception e)
                {
                    _LoadingFailure = e.Message;
                    _LoadingStatus  = LoadingStatus.Completed;
                }
            }

            // Complete Loading status
            if (_LoadingStatus == LoadingStatus.WaitingForSceneDeserialization)
            {
                if (_EntityManager.ExclusiveEntityTransactionDependency.IsCompleted)
                {
                    _EntityManager.ExclusiveEntityTransactionDependency.Complete();

                    _LoadingStatus = LoadingStatus.Completed;
                    var currentTime = Time.realtimeSinceStartup;
                    var totalTime   = currentTime - _StartTime;
                    System.Console.WriteLine($"Streamed scene with {totalTime * 1000,3:f0}ms latency from {_ScenePath}");
                }
            }
        }
Example #23
0
 void _StopLoadAsync()
 {
     m_CreateRequest = null;
     m_step          = EnumLoadStep.None;
 }
        /// <summary>Gets a bundle using the given bundle URI.</summary>
        private void LoadBundle(Location uri, BundleReadyEvent bre)
        {
            // Main thread only. (Even things like bund!=null can fail).
            Callback.MainThread(delegate(){
                // The underlying uri is uri.Path.
                string path = uri.Path;

                // Loading or loaded?
                AssetBundle bund = Bundles.Get(path);

                if (bund != null)
                {
                    bre(bund);
                    return;
                }

                DataPackage package;

                if (Bundles.Loading.TryGetValue(path, out package))
                {
                    // Loading - just add a listener (always runs after the bundle loading callback):
                    package.addEventListener("onload", delegate(UIEvent e){
                        // Callback:
                        bre(Bundles.Get(path));
                    });
                }
                else
                {
                    // Make a request:
                    package = new DataPackage(path, null);

                    package.addEventListener("onload", delegate(UIEvent e){
                        // 5.4.1 onwards
                                                #if !UNITY_5_4_0 && UNITY_5_4_OR_NEWER
                        AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(package.responseBytes);
                                                #else
                        AssetBundleCreateRequest request = AssetBundle.CreateFromMemory(package.responseBytes);
                                                #endif

                        // Get the enumerator:
                        IEnumerator enumerator = Loader(request);

                        // Add updater:
                        OnUpdateCallback cb = null;

                        cb = OnUpdate.Add(delegate(){
                            // Move enumerator:
                            enumerator.MoveNext();

                            // Request done?
                            if (request.isDone)
                            {
                                // Great! Stop:
                                cb.Stop();

                                // Set now:
                                AssetBundle bundle = request.assetBundle;

                                Bundles.Add(path, bundle);

                                // Callback:
                                bre(bundle);
                            }
                        });
                    });

                    // Send now:
                    package.send();
                }
            });
        }
Example #25
0
 //读取AssetBundle
 void _ExecuteStep3()
 {
     m_CreateRequest = AssetBundle.LoadFromMemoryAsync(m_fileData);
     m_step          = EnumLoadStep.Step4;
 }
Example #26
0
        public IEnumerator LoadAB(string _assetName, string _IEName, System.Type type, System.Action <Object> _callBack)
        {
            yield return(null);

            //获取名字(服务器的文件名字,md5处理过和原先的资源名不一样)//
            string[] _list    = _IEName.Split(split, StringSplitOptions.None);
            string   _objName = _list[_list.Length - 1];
            //去掉后缀名//
            string _name = _assetName.Split(split, StringSplitOptions.None)[_assetName.Split(split, StringSplitOptions.None).Length - 1].Split('.')[0];;  // _objName.Split('.')[0];

            print("_name:" + _name);
            string _objPath = Application.persistentDataPath + "/" + _objName;
            bool   _isLocal = File.Exists(_objPath);

            if (_isLocal)
            {
            }
            else
            {
                UnityWebRequest _req = new UnityWebRequest(_IEName);
                _req.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
                _req.SendWebRequest();
                while (!_req.isDone)
                {
                    yield return(null);
                }
                File.WriteAllBytes(_objPath, _req.downloadHandler.data);
                yield return(null);

                _req.Abort();
                _req.Dispose();
            }


            //读写入的资源//
            AssetBundleCreateRequest asset = null;

            //根据路径下载对应的ab文件//
            asset = AssetBundle.LoadFromFileAsync(_objPath);
            while (!asset.isDone)
            {
                yield return(null);
            }

            Object _obj = null;

            if (asset.assetBundle != null)
            {
                AssetBundleRequest _abReq = asset.assetBundle.LoadAllAssetsAsync();
                while (!_abReq.isDone)
                {
                    yield return(null);
                }
                Object[] _objList = _abReq.allAssets;
                for (int i = 0; i < _objList.Length; i++)
                {
                    if (_objList[i].name == _name)
                    {
                        _obj = _objList[i];// Object.Instantiate(_objList[i]);
                        break;
                    }
                }
                if (_obj != null)
                {
                    if (_callBack != null)
                    {
                        _callBack.Invoke(_obj);
                    }
                }
                asset.assetBundle.Unload(false);
                asset = null;
            }

            yield return(null);

            //执行从数组中删除的操作//
            StartCoroutine(ExecIE(_IEName));
        }
        /// <summary>
        /// 异步获取AB包
        /// </summary>
        /// <param name="path"></param>
        private IProgress GetAssetBundleAsync(string path, System.Action <AssetBundle> callBack)
        {
            path = Path2Key(path);
            path = path.Replace('\\', '/');
            if (!m_ABDic.TryGetValue(path, out AssetBundle ab))
            {
                string abName = path;
                //string abName = string.IsNullOrEmpty(path) ? "" : "/" + path;

                AssetBundleCreateRequest mainRequest = AssetBundle.LoadFromFileAsync(m_ABPath + "/" + abName + m_Variant);
                m_LoadingAB.Add(abName, mainRequest);

                // 添加任务列表
                List <AssetBundleCreateRequest> requests = new List <AssetBundleCreateRequest>
                {
                    mainRequest
                };

                //string[] dependencies = m_Mainfest.GetAllDependencies(path + ".ab");
                string[] dependencies = m_DependenceInfo.GetAllDependencies(path + m_Variant);
                foreach (var name in dependencies)
                {
                    if (m_ABDic.ContainsKey(Name2Key(name)))
                    {
                        continue;
                    }
                    var request = AssetBundle.LoadFromFileAsync(m_ABPath + "/" + name);
                    requests.Add(request);
                    m_LoadingAB.Add(Name2Key(name), request);
                }

                ITask[] tasks = new ITask[requests.Count];

                for (int i = 0; i < tasks.Length; i++)
                {
                    int index = i;
                    tasks[index] = new SingleTask(() =>
                    {
                        return(requests[index].isDone);
                    });
                    tasks[index].Then(new SingleTask(() =>
                    {
                        string key = Name2Key(requests[index].assetBundle.name);
                        m_ABDic.Add(key, requests[index].assetBundle);
                        m_LoadingAB.Remove(key);
                        return(true);
                    }));
                }

                AllTask abTask = new AllTask(tasks);
                abTask.Then(new SingleTask(() =>
                {
                    callBack.Invoke(mainRequest.assetBundle);
                    return(true);
                }));
                GameEntry.GetModule <TaskManager>().StartTask(abTask);

                return(new ResProgress(requests.ToArray()));
            }
            else
            {
                callBack(ab);
                return(new DefaultProgress());
            }
        }
Example #28
0
        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;
            }

            string path = this.GetAbsolutePath();

#if UNITY_ANDROID && !UNITY_5_4_OR_NEWER
            if (this.Uri.Scheme.Equals("jar", StringComparison.OrdinalIgnoreCase))
            {
                promise.UpdateProgress(0f);
                promise.SetException(new NotSupportedException(string.Format("Failed to load the AssetBundle '{0}' at the address '{1}'.It is not supported before the Unity3d 5.4.0 version.", this.BundleInfo.Name, path)));
                yield break;
            }
#endif
            float weight    = 0;
            long  totalSize = this.BundleInfo.FileSize;
            if (this.IsRemoteUri())
            {
                weight = WEIGHT;
                string fullname = BundleUtil.GetStorableDirectory() + this.BundleInfo.Filename;
                using (UnityWebRequest www = new UnityWebRequest(path))
                {
                    www.downloadHandler = new DownloadFileHandler(fullname);
#if UNITY_2018_1_OR_NEWER
                    www.SendWebRequest();
#else
                    www.Send();
#endif
                    while (!www.isDone)
                    {
                        if (www.downloadedBytes >= 0 && totalSize > 0)
                        {
                            promise.UpdateProgress(weight * (float)www.downloadedBytes / totalSize);
                        }
                        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;
                    }
                    path = fullname;
                }
            }

            AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);
            while (!request.isDone)
            {
                promise.UpdateProgress(weight + (1 - weight) * request.progress);
                yield return(null);
            }

            var assetBundle = request.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);
        }
Example #29
0
        // TODO from stream/memory
        /// <summary>
        /// Load an avatar from a file.
        /// </summary>
        /// <param name="path">Path to the .avatar file</param>
        /// <param name="success">Action to call if the avatar is loaded successfully</param>
        /// <param name="error">Action to call if the avatar isn't loaded successfully</param>
        /// <returns><see cref="IEnumerator{AsyncOperation}"/></returns>
        public IEnumerator <AsyncOperation> FromFileCoroutine(string path, Action <LoadedAvatar> success = null, Action <Exception> error = null)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            string fullPath = Path.GetFullPath(path);

            if (!File.Exists(fullPath))
            {
                throw new IOException($"File '{fullPath}' does not exist");
            }

            // already loading, just add handlers
            if (_handlers.ContainsKey(fullPath))
            {
                _handlers[fullPath].Add(new LoadHandlers(success, error));

                yield break;
            }

            _handlers.Add(fullPath, new List <LoadHandlers> {
                new LoadHandlers(success, error)
            });

            _logger.Info($"Loading avatar from '{fullPath}'");

            AssetBundleCreateRequest assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(fullPath);

            yield return(assetBundleCreateRequest);

            if (!assetBundleCreateRequest.isDone || !assetBundleCreateRequest.assetBundle)
            {
                var exception = new AvatarLoadException("Could not load asset bundle");

                _logger.Error($"Failed to load avatar at '{fullPath}'");
                _logger.Error(exception);

                foreach (LoadHandlers handler in _handlers[fullPath])
                {
                    handler.error?.Invoke(exception);
                }

                _handlers.Remove(fullPath);

                yield break;
            }

            AssetBundleRequest assetBundleRequest = assetBundleCreateRequest.assetBundle.LoadAssetWithSubAssetsAsync <GameObject>(kGameObjectName);

            yield return(assetBundleRequest);

            if (!assetBundleRequest.isDone || assetBundleRequest.asset == null)
            {
                assetBundleCreateRequest.assetBundle.Unload(true);

                var exception = new AvatarLoadException("Could not load asset from asset bundle");

                _logger.Error($"Failed to load avatar at '{fullPath}'");
                _logger.Error(exception);

                foreach (LoadHandlers handler in _handlers[fullPath])
                {
                    handler.error?.Invoke(exception);
                }

                _handlers.Remove(fullPath);

                yield break;
            }

            assetBundleCreateRequest.assetBundle.Unload(false);

            try
            {
                var loadedAvatar = new LoadedAvatar(fullPath, (GameObject)assetBundleRequest.asset, _container.Resolve <ILoggerProvider>());

                _logger.Info($"Successfully loaded avatar '{loadedAvatar.descriptor.name}' from '{fullPath}'");

                foreach (LoadHandlers handler in _handlers[fullPath])
                {
                    handler.success?.Invoke(loadedAvatar);
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"Failed to load avatar at '{fullPath}'");
                _logger.Error(ex);

                foreach (LoadHandlers handler in _handlers[fullPath])
                {
                    handler.error?.Invoke(new AvatarLoadException("Failed to load avatar", ex));
                }
            }

            _handlers.Remove(fullPath);
        }
Example #30
0
        IEnumerator DownloadAssetBundle()
        {
            downloading = true;

            // Create and send our request
            var request = new HTTPRequest(new Uri(URL)).Send();

            status = "Download started";

            // Wait while it's finishes and add some fancy dots to display something while the user waits for it.
            // A simple "yield return StartCoroutine(request);" would do the job too.
            while (request.State < HTTPRequestStates.Finished)
            {
                yield return(new WaitForSeconds(0.1f));

                status += ".";
            }

            // Check the outcome of our request.
            switch (request.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:

                if (request.Response.IsSuccess)
                {
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
                    status = string.Format("AssetBundle downloaded! Loaded from local cache: {0}", request.Response.IsFromCache.ToString());
#else
                    status = "AssetBundle downloaded!";
#endif

                    // Start creating the downloaded asset bundle
                    AssetBundleCreateRequest async =
#if UNITY_5_3
                        AssetBundle.LoadFromMemoryAsync(request.Response.Data);
#else
                        AssetBundle.LoadFromMemoryAsync(request.Response.Data);
#endif

                    // wait for it
                    yield return(async);

                    // And process the bundle
                    yield return(StartCoroutine(ProcessAssetBundle(async.assetBundle)));
                }
                else
                {
                    status = string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                           request.Response.StatusCode,
                                           request.Response.Message,
                                           request.Response.DataAsText);
                    Debug.LogWarning(status);
                }

                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                status = "Request Finished with Error! " + (request.Exception != null ? (request.Exception.Message + "\n" + request.Exception.StackTrace) : "No Exception");
                Debug.LogError(status);
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                status = "Request Aborted!";
                Debug.LogWarning(status);
                break;

            // Ceonnecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                status = "Connection Timed Out!";
                Debug.LogError(status);
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                status = "Processing the request Timed Out!";
                Debug.LogError(status);
                break;
            }

            downloading = false;
        }
        public bool MoveNext()
        {
            if (_state == FlashCachedWwwState.Invalid)
                throw new Exception("Invalid state");

            var cache = FlashCachedWWWInitializer.FlashWWWLSOCache;
            switch (_state)
            {
                case FlashCachedWwwState.Init:
                    if (cache == null)
                        return Advance();

                    if (!cache.HasInCache(_storageName))
                        return Advance();

                    bytes = cache.GetFromCache(_storageName);
                    return AdvanceOrBranch(CrcCheckSumCorrect(), FlashCachedWwwState.AssetBundle_Create);

                case FlashCachedWwwState.WWW_StartDownload:
                    _www = new WWW(_url);
                    return Advance();

                case FlashCachedWwwState.WWW_Wait:
                    progress = _www.progress;
                    error = _www.error;
                    isDone = _www.isDone;
                    return AdvanceIf(_www.isDone);

                case FlashCachedWwwState.WWW_Complete:
                    //Dispose of WWW.
                    if (_www.error != null)
                        return AdvanceTo(FlashCachedWwwState.Complete);

                    bytes = _www.bytes;
                    _www.Dispose();
                    if (cache != null && CrcCheckSumCorrect())
                        cache.StoreInCache(_storageName, bytes);

                    return Advance();

                case FlashCachedWwwState.AssetBundle_Create:
                    if (dontCreateAssetBundle)
                        return false;

                    _request = AssetBundle.CreateFromMemory(bytes);
                    return Advance();

                case FlashCachedWwwState.AssetBundle_Complete:
                    if(_request == null)
                        throw new Exception("Failed to load asset bundle ");

                    if (_request.isDone)
                        assetBundle = _request.assetBundle;

                    return AdvanceIf(_request.isDone);
                case FlashCachedWwwState.Complete:
                    _www = null;
                    return false;
            }
            return false;
        }