Пример #1
0
    private IEnumerator LoadAssetAsync(string url, int version, AssetBundle AB, string assetName)
    {
        string keyName = abManager.MakeKeyName(url, version);

        if (!dicAsset.ContainsKey(keyName))
        {
            Dictionary <string, object> ab = new Dictionary <string, object>();
            dicAsset.Add(keyName, ab);
        }
        if (!dicAsset[keyName].ContainsKey(assetName))
        {
            AssetBundleRequest abReq = AB.LoadAssetAsync(assetName);
            while (!abReq.isDone)
            {
                yield return(null);

                UI_StartManager.instance.SetAssetLoadUIProgressbarValue(abReq.progress, assetName, UI_StartManager.instance.CurrentDownloadCount);
            }
            if (abReq.asset != null)
            {
                dicAsset[keyName].Add(assetName, abReq.asset);
                UI_StartManager.instance.CurrentDownloadCount += 1;
            }
            else
            {
                UI_StartManager.instance.ShowErrorUI(assetName + " 로드에 실패하였습니다.");
            }
        }
    }
Пример #2
0
    IEnumerator LoadAsset()
    {
        while (!Caching.ready)
        {
            yield return(null);
        }

        using (WWW www = WWW.LoadFromCacheOrDownload(path, version))
        {
            yield return(www);

            if (www.error != null)
            {
                throw new Exception("WWW download had an error:" + www.error);
            }

            AssetBundle        bundle = www.assetBundle;
            AssetBundleRequest req    = bundle.LoadAssetAsync("Cube_0", typeof(GameObject));

            yield return(req);

            GameObject obj = Instantiate(req.asset) as GameObject;
            obj.transform.position = Vector3.zero;

            bundle.Unload(false);
            www.Dispose();
        }
    }
Пример #3
0
    IEnumerator AsyncLoadSAFromAB(UnityWebRequest _uwr, Action <SpriteAtlas> _end, string _spriteAtlasName)
    {
        SpriteAtlas result = null;

        AssetBundle ab = DownloadHandlerAssetBundle.GetContent(_uwr);

        if (ab != null)
        {
            tmpAB = ab;

            var abr = ab.LoadAssetAsync <SpriteAtlas>(_spriteAtlasName);
            yield return(abr);

            if (abr.asset != null)
            {
                result = abr.asset as SpriteAtlas;
            }

            yield return(null);

            ab.Unload(false);
        }

        _end(result);

        tmpAB = null;

        yield return(null);
    }
    IEnumerator LoadAssetBundleAsset()
    {
        //unity 推荐的方式,缓存机制,如果纯粹www机制就必须每次都是在线下载,使用loadfromecaheordownload可以自动判断是否本地有缓存。ios和安卓4g,web 50m
        WWW www = WWW.LoadFromCacheOrDownload(abURL, 5);

        //等待下载完成
        yield return(www);

        //指定我定义的bunle为从网上拉下来的bundle,以便进一步操作。
        myAssetBundle = www.assetBundle;

        //异步加载对象
        AssetBundleRequest request = myAssetBundle.LoadAssetAsync("Holiday", typeof(GameObject));

        //等待加载完成
        yield return(request);

        //获取请求到的对象资源引用
        GameObject cube = request.asset as GameObject;

        //动态获取shader,防止丢失
        cube.GetComponentInChildren <Renderer>().sharedMaterial.shader = Shader.Find("Unlit/Texture");


        //从内存中卸载assebundle,false参数也是官方建议的,不直接删除,直到引用为零。
        myAssetBundle.Unload(false);

        GameObject.Instantiate(cube);
    }
Пример #5
0
        private IEnumerator LoadAnimationInfoFromAssetBundle(CreateAnimationRequest request)
        {
            Debug.Assert(m_mainBundle);
            AssetBundleRequest abRequest = m_mainBundle.LoadAssetAsync(request.prefab.name);

            yield return(abRequest);

            bool find = false;
            InstanceAnimationInfo info = null;

            if (m_animationInfo.TryGetValue(request.prefab, out info))
            {
                find = true;
                request.instance.Prepare(info.listAniInfo, info.extraBoneInfo);
            }

            if (abRequest != null && !find)
            {
                TextAsset    asset  = abRequest.asset as TextAsset;
                BinaryReader reader = new BinaryReader(new MemoryStream(asset.bytes));
                info               = new InstanceAnimationInfo();
                info.listAniInfo   = ReadAnimationInfo(reader);
                info.extraBoneInfo = ReadExtraBoneInfo(reader);
                AnimationInstancingMgr.Instance.ImportAnimationTexture(request.prefab.name, reader);
                request.instance.Prepare(info.listAniInfo, info.extraBoneInfo);
                m_animationInfo.Add(request.prefab, info);
            }
        }
Пример #6
0
    IEnumerator CignetLoad()
    {
        string path = OpenFileName.ShowDialog("all", "all");

        AssetBundleCreateRequest asyncBundleRequest = AssetBundle.LoadFromFileAsync(path);

        yield return(asyncBundleRequest);

        AssetBundle localAssetBundle = asyncBundleRequest.assetBundle;

        if (localAssetBundle == null)
        {
            Debug.LogError("Failed to load AssetBundle!");
            yield break;
        }

        AssetBundleRequest assetRequest = localAssetBundle.LoadAssetAsync <GameObject>(assetName);

        yield return(assetRequest);

        GameObject prefab = assetRequest.asset as GameObject;

        Instantiate(prefab);

        localAssetBundle.Unload(false);
    }
Пример #7
0
        private IEnumerator UnpackAssets()
        {
            string path            = Application.dataPath + "/sharedassets0.assets";
            int    versionUniqueId = SKU.CalcUniqueChangelistVersionIntRepresentation();

            using (WWW www = WWW.LoadFromCacheOrDownload("file://" + path, versionUniqueId))
            {
                yield return(www);

                if (!www.error.NullOrEmpty())
                {
                    throw new Exception("WWW download had an error:" + www.error);
                }
                AssetBundle bundle     = www.assetBundle;
                string[]    assetNames = bundle.GetAllAssetNames();
                for (int j = 0; j < assetNames.Length; j++)
                {
                    AssetBundleRequest request = bundle.LoadAssetAsync(assetNames[j], typeof(UnityEngine.Object));
                    yield return(request);

                    assets.Add(request.asset.name, request.asset);
                }
                bundle.Unload(false);
            }
        }
Пример #8
0
    private IEnumerator IELoadAssetAsync(string assetName, Action <UnityEngine.Object, LoadEventData> loadComplete, LoadEventData evData)
    {
        Debug.Log("name " + assetName);
        var ab = _bundle.LoadAssetAsync <UnityEngine.Object>(assetName);

        yield return(ab);

        // 添加资源缓存
        AddRes(assetName, ab.asset);

        if (!_loadCompleteDict.ContainsKey(assetName))
        {
            yield break;
        }

        var callbackList     = _loadCompleteDict[assetName];
        var callbackDataList = _loadEvDataDic[assetName];

        for (int i = 0; i < callbackDataList.Count; i++)
        {
            LoadCallback(callbackList[i], GetAsset(assetName), callbackDataList[i]);
            //在加载缓存的时候还存在问题,_loadCompleteDict里面Key不知道怎么会少了一个,如果解决就可以去掉注释
            //yield return 0;
            callbackList[i] = null;
        }

        callbackList     = _loadCompleteDict[assetName];
        callbackDataList = _loadEvDataDic[assetName];
        var needDelete = callbackList.TrueForAll(c => c == null);

        if (needDelete)
        {
            _loadCompleteDict.Remove(assetName);
        }
    }
Пример #9
0
    public IEnumerator LoadAssetAsync <T>(string assetBundleName, string assetName, Action <T> callback) where T : UnityEngine.Object
    {
        //未初始化先初始化
        if (!hasInit)
        {
            yield return(Init());
        }
        //加载相对应的Bundle
        yield return(LoadAssetBundle(assetBundleName));

        AssetBundle bundle = bundleDic [assetBundleName];

        AssetBundleRequest request = bundle.LoadAssetAsync <T> (assetName);

        yield return(request);

        if (request.isDone)
        {
            if (request.asset != null)
            {
                UnityEngine.Object obj = request.asset;
                callback(obj as T);
            }
            else
            {
                                #if UNITY_EDITOR
                Debug.Log("request.asset is Null");
                                #endif
                Messenger.Broadcast <string, string> (LoadEvent.AssetLoadFailed, assetBundleName, assetName);
            }
        }
    }
        /// <summary>
        /// 通过加载资源代理辅助器开始异步加载资源。
        /// </summary>
        /// <param name="resource">资源。</param>
        /// <param name="resourceChildName">要加载的子资源名。</param>
        public override void LoadAsset(object resource, string resourceChildName)
        {
            if (m_LoadResourceAgentHelperLoadCompleteEventHandler == null || m_LoadResourceAgentHelperUpdateEventHandler == null || m_LoadResourceAgentHelperErrorEventHandler == null)
            {
                Log.Fatal("Load resource agent helper handler is invalid.");
                return;
            }

            AssetBundle assetBundle = resource as AssetBundle;

            if (assetBundle == null)
            {
                m_LoadResourceAgentHelperErrorEventHandler(this, new LoadResourceAgentHelperErrorEventArgs(LoadResourceStatus.TypeError, "Can not load asset bundle from loaded resource which is not an asset bundle."));
                return;
            }

            if (string.IsNullOrEmpty(resourceChildName))
            {
                m_LoadResourceAgentHelperErrorEventHandler(this, new LoadResourceAgentHelperErrorEventArgs(LoadResourceStatus.ChildAssetError, "Can not load asset from asset bundle which child name is invalid."));
                return;
            }

            m_ResourceChildName  = resourceChildName;
            m_AssetBundleRequest = assetBundle.LoadAssetAsync(resourceChildName);
        }
Пример #11
0
        public AssetBundleRequest LoadAssetAsync <T>(string asset) where T : Object
        {
            try
            {
                asset = asset.ToLower();

                AssetBundleRequest result          = null;
                string             assetBundleName = findAssetBundleNameByAsset(asset);
                if (string.IsNullOrEmpty(assetBundleName) == false)
                {
                    AssetBundle ab = loadAssetBundleAndDependencies(assetBundleName);
                    if (ab != null)
                    {
                        result = ab.LoadAssetAsync <T>(asset);
                    }
                }

                return(result);
            }
            catch (System.Exception ex)
            {
                Debug.LogError("LoadSceneAsync.LoadAssetAsync is falid!\n" + ex.Message);
            }

            return(null);
        }
Пример #12
0
        void CreatBundleReq()
        {
            AssetBundle tasbd = mAssetsBundle as AssetBundle;
            string      tname = DeleteSuffixName(mAssetName);

            mLoadObjReq = tasbd.LoadAssetAsync(tname);
        }
Пример #13
0
    public IEnumerator IE_LoadCacheAssetAsync <T> (string bundleName, string objectName, System.Action <Object> initHandler, bool autoUnload = true)
    {
        if (m_Bundlers.ContainsKey(bundleName))
        {
            AssetBundle        ab  = m_Bundlers[bundleName];
            AssetBundleRequest abr = ab.LoadAssetAsync(objectName, typeof(T));
            yield return(abr);

            Object ob = abr.asset;
            if (ob != null && initHandler != null)
            {
                initHandler(ob);
            }
            if (autoUnload)
            {
                Unload(bundleName);
            }
        }
        else
        {
            yield return(StartCoroutine(IE_LoadCacheBundle(bundleName)));

            if (m_Bundlers.ContainsKey(bundleName))
            {
                yield return(StartCoroutine(IE_LoadAssetAsync <T>(bundleName, objectName, initHandler, autoUnload)));
            }
        }
    }
Пример #14
0
        /// <summary>
        /// [await/async] 异步
        /// </summary>
        /// <param name="ab"></param>
        /// <param name="file_Name"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private async UniTask <UnityEngine.Object> Load_Asset_From_AssetBundle_Async(AssetBundle ab, string file_Name, Type type)
        {
            var   req = ab.LoadAssetAsync(file_Name, type);
            await req;

            return(req.asset);
        }
Пример #15
0
    IEnumerator Start()
    {
        WWW www = new WWW(url);

        yield return(www);

        AssetBundle        bundle = www.assetBundle;
        AssetBundleRequest req    = bundle.LoadAssetAsync("cube", typeof(GameObject));

        yield return(request);

        GameObject cube = req.asset as GameObject;

        bundle.Unload(false);
        www.Dispose();

/*
 *      if (AssetName == "") {
 *          Instantiate(bundle.mainAsset);
 *      } else {
 *          Instantiate(bundle.LoadAsset(AssetName));
 *          bundle.Unload(false);
 *      }
 */
    }
Пример #16
0
    public static IEnumerable GetAssetAsyncE(string path, Type type, Action <AsyncOperation> onComplete)
    {
        if (path == string.Empty)
        {
            Debug.LogError("bundle path is null");
            yield return(0);
        }

        AssetBundle ab = null;

        if (!Instance.bundleMap.TryGetValue(path, out ab))
        {
            ab = Instance.LoadAssetBundleByPath(GetPath(path.ToString()));
            if (ab == null)
            {
                Debug.LogError("find not bundle: " + path);
                yield return(0);
            }
            Instance.bundleMap[path] = ab;
        }

        path = GetAssetName(path);
        AssetBundleRequest req = ab.LoadAssetAsync(path, type);

        yield return(req);

        if (onComplete != null)
        {
            req.completed += onComplete;
        }

        yield return(0);
    }
Пример #17
0
        IEnumerator LoadAssetAsync <T>(string assetName, Action <T> loadedCallBack) where T : Object
        {
            if (assetBundle == null && loadedCallBack != null)
            {
                loadedCallBack(null);
                yield break;
            }

            AssetBundleRequest assetBundleRequest;
            Object             loadAsset;

            assetObjects.TryGetValue(assetName, out loadAsset); //缓存以后的速度快好多了
            if (loadAsset == null)
            {
                assetBundleRequest = assetBundle.LoadAssetAsync <T>(assetName);
                yield return(assetBundleRequest);

                loadAsset = assetBundleRequest.asset;
            }
            T asset = loadAsset as T;

            if (asset != null && loadedCallBack != null)
            {
                loadedCallBack(asset);
            }
        }
Пример #18
0
    /// <summary>
    /// 加载资源
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="assetBundleName"></param>
    /// <param name="assetName"></param>
    /// <param name="isWait"></param>
    /// <returns></returns>
    private T _LoadAsset <T>(string assetBundleName, string assetName = null, bool isWait = false) where T : UObject
    {
#if UNITY_EDITOR
        if (SimulateAssetBundleInEditor == false)
        {
            string[] assetPaths = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(assetBundleName, assetName);
            if (assetPaths.Length == 0)
            {
                Debug.LogError("There is no asset with name \"" + assetName + "\" in " + assetBundleName);
                return(null);
            }
            // @TODO: Now we only get the main object from the first asset. Should consider type also.
            UObject target = AssetDatabase.LoadMainAssetAtPath(assetPaths[0]);
            return(target as T);
        }
        else
#endif

        {
            AssetBundle assetBundle = LoadAssetBundle(assetBundleName);
            T           obj         = (T)assetBundle.LoadAssetAsync <T>(assetName).asset;
            if (obj == null)
            {
                Debug.LogError($"加载资源失败:{assetBundleName}  AssName:{assetName}");
            }
            return(obj);
        }
    }
Пример #19
0
    /// <summary>
    /// 从远程服务器上下载加载资源
    /// </summary>
    /// <returns></returns>
    IEnumerator DownloadFromServer()
    {
        while (Caching.ready == false) //查看是否缓存是否准备好了
        {
            yield return(null);        //暂停一帧
        }

        //需要写完整的路径,如果是远程服务器则是http协议,写好ip地址,注意是三或两个斜杠
        System.String path = @"http://localhost/AssetBundles/reply/spherestone";

        WWW www = WWW.LoadFromCacheOrDownload(path, 1); //第二个参数是版本

        yield return(www);                              //等待返回,即等待下载完成

        if (string.IsNullOrEmpty(www.error) == false)   //如果下载有错误则显示错误
        {
            Debug.Log(www.error);
            yield break;    //结束协程
        }

        AssetBundle ab = www.assetBundle;  //获得从网络下载的资源
        //使用获得的资源

        AssetBundleRequest g = ab.LoadAssetAsync <GameObject>("SphereStone.prefab");

        yield return(g);

        Instantiate(g.asset);  //实例化这个对象到场景中
    }
Пример #20
0
    IEnumerator LoadBundle(string clubhouseName)
    {
        while (!Caching.ready)
        {
            yield return(null);
        }

        //Begin download
        WWW www = WWW.LoadFromCacheOrDownload(url, 0);

        yield return(www);

        //Load the downloaded bundle
        AssetBundle bundle = www.assetBundle;

        //Load an asset from the loaded bundle
        AssetBundleRequest bundleRequest = bundle.LoadAssetAsync(clubhouseName, typeof(GameObject));

        yield return(bundleRequest);

        //get object
        GameObject obj = bundleRequest.asset as GameObject;

        clubhouseGO      = Instantiate(obj, spawnPos.position, Quaternion.identity) as GameObject;
        loadingText.text = "";

        bundle.Unload(false);
        www.Dispose();
    }
Пример #21
0
    public void call1(string url, string names)
    {
        StartCoroutine(Start());
        IEnumerator Start()
        {
            var uwr = UnityWebRequestAssetBundle.GetAssetBundle(url);

            yield return(uwr.SendWebRequest());

            // Get an asset from the bundle and instantiate it.


            bundle = DownloadHandlerAssetBundle.GetContent(uwr);



            string bun       = "assets/" + names + ".fbx";
            var    loadAsset = bundle.LoadAssetAsync <GameObject>(bun);

            yield return(loadAsset);

            childobj1 = (GameObject)Instantiate(loadAsset.asset) as GameObject;
            childobj1.transform.localScale /= 500;
            Debug.Log(childobj1.name);
            childobj1.transform.position = childobj.transform.position;
            childobj1.transform.rotation = childobj.transform.rotation;
            childobj1.transform.parent   = childobj.transform;

            bundle.Unload(false);
        }
    }
Пример #22
0
    public IEnumerator LoadBundleAsset <T>(string assetPath, int version, uint crc, string assetName)
        where T : UnityEngine.Object
    {
        while (mAssetLocker.IsLock(assetPath))
        {
            yield return(null);
        }

        mAssetLocker.Lock(assetPath);

        mObj = null;
        yield return(Globals.Instance.StartCoroutine(LoadBundleFunc(assetPath, version, crc)));

        if (mAssetBundle == null)
        {
            Debug.LogWarning("assetBundle is null!");
            yield return(null);
        }
        else
        {
            if (string.IsNullOrEmpty(assetName))
            {
                mObj = mAssetBundle.mainAsset;
            }
            else
            {
                AssetBundleRequest assetReq = mAssetBundle.LoadAssetAsync(assetName, typeof(T));
                yield return(assetReq);

                mObj = assetReq.asset;
            }
        }

        mAssetLocker.UnLock(assetPath);
    }
Пример #23
0
    // Update is called once per frame
    IEnumerator GetAssetBundle()
    {
        UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle("https://storage.googleapis.com/adrop/model.cube");

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
            Debug.Log("get bundle content successfully");
            // UnityEngine.Object[] temp = bundle.LoadAllAssets();
            // placeObject = (GameObject) temp[0];
            // Debug.Log("convert to placeObject successfully");
            // Instantiate(temp[0], placementPose.position, placementPose.rotation);

            AssetBundleRequest request = bundle.LoadAssetAsync("model.cube", typeof(GameObject));
            Debug.Log("begin load request");
            // Wait for completion
            yield return(request);

            GameObject obj = request.asset as GameObject;
            Debug.Log("transform to obj successfully");
            Instantiate(obj, placementPose.position, placementPose.rotation);
            Debug.Log("Instantiate successfully");
        }
    }
Пример #24
0
    IEnumerator GetAssetBundle()
    {
        UnityWebRequest www = UnityWebRequest.GetAssetBundle(home.url);

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
            Debug.Log("Success");
            bundle.LoadAllAssetsAsync();
            foreach (var name in bundle.GetAllAssetNames())
            {
                Debug.Log(name);

                AssetBundleRequest request = bundle.LoadAssetAsync(name, typeof(GameObject));

                yield return(request);

                GameObject obj = request.asset as GameObject;
                GameObject.Instantiate(obj);
                bundle.Unload(false);
            }
            RestoreAll(LightmapsMode.CombinedDirectional, false, true);
            GameObject.FindObjectOfType <Customizer> ().initialize();
        }
    }
Пример #25
0
        /// <summary>
        /// 加载Asset
        /// </summary>
        /// <param name="abName"></param>
        /// <param name="assetType"></param>
        /// <returns></returns>
        IEnumerator OnLoadAsset(string abName, Type assetType)
        {
            AssetBundleData bundleData = GetLoadedAssetBundle(abName);

            if (bundleData == null)
            {
                yield return(StartCoroutine(OnLoadAssetBundle(abName, assetType)));

                bundleData = GetLoadedAssetBundle(abName);
                if (bundleData == null)
                {
                    m_loadRequests.Remove(abName);
                    Debug.LogError("OnLoadAsset-->>" + abName);
                    yield break;
                }
            }

            List <LoadAssetRequest> list = null;

            if (!m_loadRequests.TryGetValue(abName, out list))
            {
                m_loadRequests.Remove(abName);
            }

            for (int i = 0; i < list.Count; i++)
            {
                string[]      assetNames = list[i].assetNames;
                List <Object> result     = new List <Object>();

                AssetBundle ab = bundleData.assetBundle;
                if (assetNames != null)
                {
                    for (int j = 0; j < assetNames.Length; j++)
                    {
                        string assetPath = assetNames[i];
                        var    request   = ab.LoadAssetAsync(assetPath, assetType);
                        yield return(request);

                        result.Add(request.asset);
                    }
                }
                else
                {
                    var request = ab.LoadAllAssetsAsync();
                    yield return(request);

                    result = new List <Object>(request.allAssets);
                }

                if (list[i].callback != null)
                {
                    list[i].callback(result.ToArray());
                    list[i].callback = null;
                }

                bundleData.referencedCount++;
            }

            m_loadRequests.Remove(abName);
        }
Пример #26
0
    static int LoadAssetAsync(IntPtr L)
    {
        int count = LuaDLL.lua_gettop(L);

        if (count == 2)
        {
            AssetBundle        obj  = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
            string             arg0 = LuaScriptMgr.GetLuaString(L, 2);
            AssetBundleRequest o    = obj.LoadAssetAsync(arg0);
            LuaScriptMgr.PushObject(L, o);
            return(1);
        }
        else if (count == 3)
        {
            AssetBundle        obj  = (AssetBundle)LuaScriptMgr.GetUnityObjectSelf(L, 1, "AssetBundle");
            string             arg0 = LuaScriptMgr.GetLuaString(L, 2);
            Type               arg1 = LuaScriptMgr.GetTypeObject(L, 3);
            AssetBundleRequest o    = obj.LoadAssetAsync(arg0, arg1);
            LuaScriptMgr.PushObject(L, o);
            return(1);
        }
        else
        {
            LuaDLL.luaL_error(L, "invalid arguments to method: AssetBundle.LoadAssetAsync");
        }

        return(0);
    }
            public InternalProviderOperation <TObject> Start(IResourceLocation location, IAsyncOperation <IList <object> > loadDependencyOperation)
            {
                m_Result                           = null;
                m_RequestOperation                 = null;
                m_DependencyOperation              = loadDependencyOperation;
                loadDependencyOperation.Completed += op =>
                {
                    if (op.Status == AsyncOperationStatus.Succeeded)
                    {
                        AssetBundle bundle = op.Result[0] as AssetBundle;
                        if (bundle == null)
                        {
                            var handler = op.Result[0] as DownloadHandlerAssetBundle;
                            if (handler != null)
                            {
                                bundle = handler.assetBundle;
                            }
                        }

                        if (bundle == null)
                        {
                            //TODO - handle error case properly
                            SetResult(default(TObject));
                            OnComplete();
                        }
                        else
                        {
                            var t = typeof(TObject);
                            if (t.IsArray)
                            {
                                m_RequestOperation = bundle.LoadAssetWithSubAssetsAsync(location.InternalId, t.GetElementType());
                            }
                            else if (t.IsGenericType && typeof(IList <>) == t.GetGenericTypeDefinition())
                            {
                                m_RequestOperation = bundle.LoadAssetWithSubAssetsAsync(location.InternalId, t.GetGenericArguments()[0]);
                            }
                            else
                            {
                                m_RequestOperation = bundle.LoadAssetAsync <TObject>(location.InternalId);
                            }

                            if (m_RequestOperation.isDone)
                            {
                                DelayedActionManager.AddAction((Action <AsyncOperation>)OnComplete, 0, m_RequestOperation);
                            }
                            else
                            {
                                m_RequestOperation.completed += OnComplete;
                            }
                        }
                    }
                    else
                    {
                        m_Error = op.OperationException;
                        SetResult(default(TObject));
                        OnComplete();
                    }
                };
                return(base.Start(location));
            }
Пример #28
0
        private IEnumerator m_LoadAssetWithCacheAsync <T>(string name, Action <T> callback) where T : UnityEngine.Object
        {
            // 先判断一次 是否存在
            if (CacheDic.ContainsKey(name))
            {
                callback(CacheDic[name] as T);
            }
            else
            {
                AssetBundleRequest request = assetBundle.LoadAssetAsync <T>(name);
                yield return(request);

                //因为是异步的所以 可能出现多次加载的问题 所以 再判断一次是否存在
                if (CacheDic.ContainsKey(name))
                {
                    callback(CacheDic[name] as T);
                }
                //如果还是没有 那么就加载asset 并且放到缓存里
                else
                {
                    T t1 = request.asset as T;
                    if (t1 != null)
                    {
                        CacheDic.Add(name, t1);
                        callback(t1);
                    }
                    else
                    {
                        callback(null);
                    }
                }
            }
        }
Пример #29
0
 override public IEnumerator LoadAssetAsync(AssetBundle assetBundlep, string assetName)
 {
     assetBundle        = assetBundlep;
     assetBundleRequest = assetBundle.LoadAssetAsync(assetName);
     yield return(assetBundleRequest);
     //isDone = true;
 }
        /// <summary>
        /// 通过加载资源代理辅助器开始异步加载资源。
        /// </summary>
        /// <param name="resource">资源。</param>
        /// <param name="resourceChildName">要加载的子资源名。</param>
        /// <param name="isScene">要加载的资源是否是场景。</param>
        public override void LoadAsset(object resource, string resourceChildName, bool isScene)
        {
            if (m_LoadResourceAgentHelperLoadCompleteEventHandler == null || m_LoadResourceAgentHelperUpdateEventHandler == null || m_LoadResourceAgentHelperErrorEventHandler == null)
            {
                Log.Fatal("Load resource agent helper handler is invalid.");
                return;
            }

            AssetBundle assetBundle = resource as AssetBundle;

            if (assetBundle == null)
            {
                m_LoadResourceAgentHelperErrorEventHandler(this, new LoadResourceAgentHelperErrorEventArgs(LoadResourceStatus.TypeError, "Can not load asset bundle from loaded resource which is not an asset bundle."));
                return;
            }

            if (string.IsNullOrEmpty(resourceChildName))
            {
                m_LoadResourceAgentHelperErrorEventHandler(this, new LoadResourceAgentHelperErrorEventArgs(LoadResourceStatus.ChildAssetError, "Can not load asset from asset bundle which child name is invalid."));
                return;
            }

            m_ResourceChildName = resourceChildName;
            if (isScene)
            {
                int    sceneNamePosition = resourceChildName.IndexOf('.');
                string sceneName         = sceneNamePosition > 0 ? resourceChildName.Substring(0, sceneNamePosition) : resourceChildName;
                m_AsyncOperation = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
            }
            else
            {
                m_AssetBundleRequest = assetBundle.LoadAssetAsync(resourceChildName);
            }
        }
Пример #31
0
    /// <summary>
    /// In this function we can do whatever we want with the freshly downloaded bundle.
    /// In this example we will cache it for later use, and we will load a texture from it.
    /// </summary>
    IEnumerator ProcessAssetBundle(AssetBundle bundle)
    {
        if (bundle == null)
            yield break;

        // Save the bundle for future use
        cachedBundle = bundle;

        // Start loading the asset from the bundle
        var asyncAsset = 
#if UNITY_5
            cachedBundle.LoadAssetAsync("9443182_orig", typeof(Texture2D));
#else
        
            cachedBundle.LoadAsync("9443182_orig", typeof(Texture2D));
#endif

        // wait til load
        yield return asyncAsset;

        // get the texture
        texture = asyncAsset.asset as Texture2D;
    }