/// <summary> /// Begin load /// </summary> /// <param name="asset"></param> /// <param name="resName"></param> /// <returns></returns> public IEnumerator GoLoader(AssetBundle asset, string resName) { this.m_cRequest = asset.LoadAsync(resName, typeof(UnityEngine.Object)); for (; !this.m_cRequest.isDone; ) yield return this.m_cRequest; GameObject.Destroy(this.gameObject); }
private void AssetLoadedHandler(AssetBundleRequest request) { Debug.Log("Asset loaded: " + request.asset.name); _object = (GameObject)Instantiate(request.asset); // add mouse orbit GameObject cameraGo = GameObject.Find("Main Camera"); if (null != cameraGo){ MouseOrbitCs mouseOrbit = cameraGo.AddComponent<MouseOrbitCs>(); mouseOrbit.Target = _object.transform; } }
// Wait for the Caching system to be ready IEnumerator LoadFromFile(string gameCodeName) { while (!Caching.ready) yield return null; // Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache using (www = WWW.LoadFromCacheOrDownload(_localizationFile, 1)) { #if UNITY_ANDROID || UNITY_EDITOR if (DeviceDetector.device == DeviceDetector.Device.Android && MainScript.isCurrentActivity) { activity.Call("onGameBundleLoadStart", gameCodeName); } #endif yield return www; if (www.error != null) { #if UNITY_ANDROID || UNITY_EDITOR if (DeviceDetector.device == DeviceDetector.Device.Android && MainScript.isCurrentActivity) { activity.Call("onGameBundleLoadError", new object[] { gameCodeName, www.error }); } #endif throw new Exception("WWW download had an error:" + www.error); } bundle = www.assetBundle; assetRequest = bundle.LoadAllAssetsAsync(); yield return assetRequest; if (assetRequest.isDone == true) { #if UNITY_ANDROID || UNITY_EDITOR if (DeviceDetector.device == DeviceDetector.Device.Android && MainScript.isCurrentActivity) { activity.Call("onGameBundleLoadComplete", gameCodeName); } #endif LoadScene(); } } }
public void SetRequest(AssetBundleRequest request) { bundleRequest = request; bundleRequest.completed += OnBundleLoadFinish; }
public static AssetBundleRequestAllAssetsAwaiter AwaitForAllAssets(this AssetBundleRequest asyncOperation) { Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); return(new AssetBundleRequestAllAssetsAwaiter(asyncOperation)); }
/// <summary> /// According to LoadType, it will download or load local sync /// 把AssetBundle载入内存,之后再异步Load出来,之后再次删除Assetbundle内存镜像. /// </summary> /// <returns>The load coroutine.</returns> /// <param name="task">Task.</param> private IEnumerator AsyncLoadCoroutine(AssetTask task) { bool errorOcurred = false; string assetBundleName = task.AssetBundleName; string url = ResourceSetting.ConverToFtpPath(assetBundleName); int verNum = 1;//Core.Data.sourceManager.getNewNum(assetBundleName + ".unity3d"); // 添加引用 RefAsset(assetBundleName); if (Caching.IsVersionCached(url, verNum) == false) { //ConsoleEx.DebugLog("Version Is not Cached, which will download from net!"); } WWW www = null; try { www = WWW.LoadFromCacheOrDownload(url, verNum); } catch (Exception ex) { errorOcurred = true; // ConsoleEx.DebugLog("LoadFromCacheOrDownload Error : " + ex.ToString()); if (task.LoadError != null) { task.LoadError("[" + assetBundleName + "]:" + ex.ToString()); } } if (!errorOcurred) { dicLoadingReq.Add(assetBundleName, www); while (www.isDone == false) { if ((task.LoadType == AssetTask.loadType.Only_Download || task.LoadType == AssetTask.loadType.Both_Download_loadlocal) && task.reportProgress != null) { task.reportProgress(www.progress); } yield return(null); } // Print the error to the console if (!String.IsNullOrEmpty(www.error)) { //ConsoleEx.DebugLog("["+assetBundleName+"]"+www.error); Debug.LogError("[" + assetBundleName + "]" + www.error); if (task.LoadError != null) { task.LoadError(www.error); } dicLoadingReq.Remove(assetBundleName); errorOcurred = true; } bool TaskEnd = false; if (task.LoadType == AssetTask.loadType.Only_loadlocal || task.LoadType == AssetTask.loadType.Both_Download_loadlocal) { if (!errorOcurred) { AssetBundleRequest req = www.assetBundle.LoadAsync(task.PrefabName, task.UType); while (req.isDone == false) { yield return(null); } dicAsset.Add(assetBundleName, req.asset); task.Obj = req.asset; dicLoadingReq.Remove(assetBundleName); www.assetBundle.Unload(false); //--- load local finished --- TaskEnd = true; } } else { dicLoadingReq.Remove(assetBundleName); //--- Downloading finished --- TaskEnd = true; } //release memeory if (www != null) { www.Dispose(); www = null; } //start to callback if (TaskEnd) { LoadEnd(); if (task.LoadFinished != null) { task.LoadFinished(task); } } } }
private IEnumerator PerformAsyncLoad(AssetAsyncRequest request) { AssetBundleRequest req = null; switch (request.assetRequestType) { case AssetRequestType.Part: for (int i = 0; i < request.assetTypeArray.Length; ++i) { req = request.assetBundleInfoNode.LoadAssetAsync(request.assetNameArray[i], request.assetTypeArray[i]); yield return(req); if (req.asset == null) { request.error = true; } else if (request.assetDic != null) { request.assetDic[request.assetNameArray[i]] = req.asset; } } break; case AssetRequestType.Part_SameType: for (int i = 0; i < request.assetTypeArray.Length; ++i) { req = request.assetBundleInfoNode.LoadAssetAsync(request.assetNameArray[i], request.assetType); yield return(req); if (req.asset == null) { request.error = true; } else if (request.assetDic != null) { request.assetDic[request.assetNameArray[i]] = req.asset; } } break; case AssetRequestType.All: req = request.assetBundleInfoNode.LoadAllAssetsAsync(); yield return(req); if (req.allAssets != null) { if (request.assetDic != null) { for (int j = 0; j < req.allAssets.Length; j++) { request.assetDic[req.allAssets[j].name] = req.allAssets[j]; } } } else { request.error = true; } break; default: break; } request.AssetsReady(); asyncLoadingList.Remove(request); }
protected override void OnDispose() { base.OnDispose(); abRequest = null; loadState = 0; }
public override bool IsDone() { // 如果有依赖,要先判断依赖是否已经加载完成 if (this.dependences != null) { for (int i = 0; i < this.dependences.Length; ++i) { if (!ResMgr.Instance().IsLoadedAssetBundle(this.dependences[i])) return false; } } // 判断自己是否加载完成 if (base.LoadDoneCallback == null) { // 依赖资源,不需要LoadDone回调 if (this.assetbundle != null) return true; if (this.www.isDone) { this.assetbundle = this.www.assetBundle; this.www.Dispose(); this.www = null; return true; } return false; } else { // 直接资源,需要LoadDone回调,所以需要从AssetBundle中提取资源对象 if (this.assetbundleReq != null) { // 只有从assetbundle中提取出最终的资源对象,才算加载完成,保证所有的IO操作都是异步的 return this.assetbundleReq.isDone; } else { if (this.www.isDone) { this.assetbundle = this.www.assetBundle; // 从assetbundle中提取资源对象 string resPath = string.Format(ResMgr.AssetBundleFormation, base.ResName); this.assetbundleReq = this.assetbundle.LoadAssetAsync(resPath); this.www.Dispose(); this.www = null; } return false; } } }
internal override bool Update() { if (!base.Update()) { return(false); } if (loadState == LoadState.Init) { return(true); } if (_request == null) { if (!BundleRequest.isDone) { return(true); } if (OnError(BundleRequest)) { return(false); } for (int i = 0; i < children.Count; i++) { var item = children[i]; if (!item.isDone) { return(true); } if (OnError(item)) { return(false); } } var assetName = Path.GetFileName(name); _request = BundleRequest.assetBundle.LoadAssetAsync(assetName, assetType); if (_request == null) { error = "request == null"; loadState = LoadState.Loaded; return(false); } return(true); } else { if (_request.isDone) { asset = _request.asset; loadState = LoadState.Loaded; if (asset == null) { error = "asset == null"; } return(false); } return(true); } }
protected IEnumerator loadAssetBundleCoroutine(AssetBundleInfo bundleInfo, bool loadFromWWW) { ++mAssetBundleCoroutineCount; UnityUtility.logInfo(bundleInfo.mBundleName + " start load bundle", LOG_LEVEL.LL_NORMAL); // 先确保依赖项全部已经加载完成,才能开始加载当前请求的资源包 while (!bundleInfo.isAllParentLoaded()) { yield return(null); } AssetBundle assetBundle = null; // 通过www加载 if (loadFromWWW) { #if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_IPHONE || UNITY_IOS string path = "file:\\" + CommonDefine.F_STREAMING_ASSETS_PATH + bundleInfo.mBundleName + CommonDefine.ASSET_BUNDLE_SUFFIX; #elif UNITY_ANDROID string path = "file:\\" + Application.dataPath + "!assets/" + bundleInfo.mBundleName + CommonDefine.ASSET_BUNDLE_SUFFIX; #endif WWW www = new WWW(path); yield return(www); assetBundle = www.assetBundle; www.Dispose(); www = null; } // 直接从文件加载 else { AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(CommonDefine.F_STREAMING_ASSETS_PATH + bundleInfo.mBundleName + CommonDefine.ASSET_BUNDLE_SUFFIX); if (request == null) { UnityUtility.logError("can not load asset bundle async : " + bundleInfo.mBundleName); --mAssetBundleCoroutineCount; yield break; } yield return(request); assetBundle = request.assetBundle; } // 异步加载其中所有的资源 foreach (var item in bundleInfo.mAssetList) { AssetBundleRequest assetRequest = assetBundle.LoadAssetAsync(CommonDefine.P_RESOURCE_PATH + item.Value.mAssetName); if (assetRequest == null) { UnityUtility.logError("can not load asset async : " + item.Value.mAssetName); --mAssetBundleCoroutineCount; yield break; } yield return(assetRequest); item.Value.mAssetObject = assetRequest.asset; } UnityUtility.logInfo(bundleInfo.mBundleName + " load bundle done", LOG_LEVEL.LL_NORMAL); GC.Collect(); // 通知AssetBundleInfo bundleInfo.notifyAssetBundleAsyncLoadedDone(assetBundle); --mAssetBundleCoroutineCount; }
private IEnumerator LoadScreen(string screenId, string screenPath) { GameObject newScreen; PreviousScreenID = currentScreen.screenId; // when running on webgl; only load game screen from resource if ((Application.platform != RuntimePlatform.WebGLPlayer && PersistentModel.Instance.RunLocation != PersistentModel.RUN_LOCATION.Client) || screenId == GAME_SCREEN) { ResourceRequest resourceRequest = Resources.LoadAsync <BaseScreen>(screenPath); while (!resourceRequest.isDone) { yield return(null); } transitioningScreenId = screenId; transitioningScreen = Instantiate <BaseScreen>(resourceRequest.asset as BaseScreen, transform); transitioningScreen.transform.SetAsFirstSibling(); transitioningScreen.Initialize(screenId); // loading is complete if (ProgressLoadingPanel) { ProgressLoadingPanel.GetComponent <ProgressLoadingPanel>().LoadingPercent.text = "100%"; } } else { string url = PersistentModel.Instance.AssetBundlesURL + screenId.ToLower(); UnityWebRequest request = new UnityWebRequest(url) { downloadHandler = new DownloadHandlerAssetBundle(url, 1, 0), certificateHandler = new SSLAuth() }; request.SendWebRequest(); while (!request.isDone) { ProgressLoadingPanel.GetComponent <ProgressLoadingPanel>().LoadingPercent.text = Mathf.CeilToInt(request.downloadProgress * 100).ToString() + "%"; yield return(waitSecAssetLoad); } AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request); AssetBundleRequest bundleRequest = bundle.LoadAssetAsync(screenId); yield return(bundleRequest); newScreen = Instantiate <GameObject>(bundleRequest.asset as GameObject); bundle.Unload(false); ProgressLoadingPanel.GetComponent <ProgressLoadingPanel>().LoadingPercent.text = "100%"; // Wait for the load yield return(newScreen); // add Parent, and Add it in the 1st index of Parent // so that we can have the new screen behind the current screen newScreen.transform.SetParent(transform, false); newScreen.transform.SetAsFirstSibling(); newScreen.GetComponent <BaseScreen>().Initialize(screenId); // add to list transitioningScreenId = screenId; transitioningScreen = newScreen.GetComponent <BaseScreen>(); } // isLoadingRequiredBeforeDraw is when loading the game screen and track if (!transitioningScreen.isLoadingRequiredBeforeDraw) { if (currentScreen != null) { Color activeColor = currentScreen.gameObject.GetComponent <Image>().color; activeColor.a = 1f; // fadeout background image color from screen LeanTween.value(1f, 0f, 0.75f) .setDelay(0.25f) .setEase(LeanTweenType.easeOutQuad) .setOnUpdate((float val) => { activeColor.a = val; currentScreen.gameObject.GetComponent <Image>().color = activeColor; }) .setOnComplete(() => { // ignore closing sequence, start transition in right away after race. if (screenId == CONGRATULATIONS_SCREEN) { ShowTransitionedScreen(); } else { // scales and fades in side panels // transitioningScreen.ScaleInPanels(); LeanTween.delayedCall(0.5f, transitioningScreen.ScaleInPanels); // add event when loading close sequence is complete currentScreen.OnCloseLoadingPanelComplete += CurrentScreen_OnCloseLoadingPanelComplete; // start Close Panel sequence currentScreen.CloseLoadingPanel(); } }); } else { Color activeColor = transitioningScreen.gameObject.GetComponent <Image>().color; activeColor.a = 1f; // fadeout background image color from screen LeanTween.value(1f, 0f, 0.15f) .setDelay(0.0f) .setEase(LeanTweenType.easeOutQuad) .setOnUpdate((float val) => { activeColor.a = val; transitioningScreen.gameObject.GetComponent <Image>().color = activeColor; }) .setOnComplete(() => { // scales and fades in side panels transitioningScreen.ScaleInPanels(); LeanTween.delayedCall(0.65f, ShowTransitionedScreen); }); // ShowTransitionedScreen(); yield return(0); } } else { ShowTransitionedScreen(); } }
public override void Reset() { base.Reset(); m_Request = null; }
public override void Excute(FageStateMachine stateMachine) { base.Excute (stateMachine); FageBundleLoader loader = stateMachine as FageBundleLoader; if (request != null) { if (request.isDone) { string name = queueAsset.Dequeue() as string; loader.GetLoadedAssets().Add(name, request.asset); request = null; } } else { if ((queueAsset == null) || (queueAsset.Count == 0)) { if (queueBundle.Count > 0) { AssetBundle ab = queueBundle.Dequeue() as AssetBundle; loader.GetLoadedBundles().Add(ab.name); } if ((queueBundle == null) || (queueBundle.Count == 0)) { loader.ReserveState("FageBundleLoaderIdle"); loader.SetUpdateTime(); loader.DispatchEvent(new FageEvent(FageEvent.COMPLETE)); } else { AssetBundle ab = queueBundle.Peek() as AssetBundle; queueAsset = new Queue(ab.GetAllAssetNames()); } } else { AssetBundle ab = queueBundle.Peek() as AssetBundle; string name = queueAsset.Peek() as string; request = ab.LoadAssetAsync(name); } } }
IEnumerator LoadTexture(string _name) { _loadText.text = "Загрузка пространства..."; www = WWW.LoadFromCacheOrDownload(url, 2); //www = WWW.LoadFromCacheOrDownload(url, Hash128.Parse("52493182f0ca7528471e1f270211472b")); _loadStatus = 1; yield return www; if (www.isDone == true){ _loadText.text = ""; } if (www.error != null){ _loadText.text = "WWW download had an error: " + www.error; throw new Exception("WWW download had an error: " + www.error); } _loadStatus = 0; AssetBundle bundle = www.assetBundle; string[] names = bundle.GetAllAssetNames(); foreach(string nm in names){ Debug.Log(nm); } request = bundle.LoadAssetAsync (_name + ".jpg", typeof(Texture)); if (request.isDone == true) { Debug.Log("Found in memory."); _loadText.text = ""; } else{ _loadStatus = 2; } //AssetBundleRequest request = bundle.LoadAssetAsync (names[0], typeof(Texture)); // Wait for completion yield return request; if (www.error != null){ //_loadText.text = "WWW download had an error: " + www.error; throw new Exception("WWW download had an error: " + www.error); } _loadStatus = 0; _loadText.text = ""; Texture tex = request.asset as Texture; //_loadText.text = "Loaded texture name: " + tex.name; //_texTest.GetComponent<Renderer>().material.mainTexture = tex; _currentSpace.material.mainTexture = tex; _manager.RoomLoaded(_currentSpace.GetComponent<SpaceObj>()); //iTween.CameraFadeTo(0.0f, 1.0f); StartFadeOut(); // Unload the AssetBundles compressed contents to conserve memory bundle.Unload(false); // Frees the memory from the web stream www.Dispose(); }
public override IEnumerator DoLoadAsync(System.Action finishCallback) { if (RefCount <= 0) { OnResLoadFaild(); finishCallback(); yield break; } //Object obj = null; var abR = ResMgr.Instance.GetRes <AssetBundleRes>(AssetBundleName); #if UNITY_EDITOR if (SimulateAssetBundleInEditor && !string.Equals(mAssetName, "assetbundlemanifest")) { var assetPaths = UnityEditor.AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(abR.AssetName, mAssetName); if (assetPaths.Length == 0) { Log.E("Failed Load Asset:" + mAssetName); OnResLoadFaild(); finishCallback(); yield break; } //确保加载过程中依赖资源不被释放:目前只有AssetRes需要处理该情况 HoldDependRes(); mAsset = UnityEditor.AssetDatabase.LoadAssetAtPath <Object>(assetPaths[0]); UnHoldDependRes(); } else #endif { if (abR == null || abR.AssetBundle == null) { Log.E("Failed to Load Asset, Not Find AssetBundleImage:" + AssetBundleName); OnResLoadFaild(); finishCallback(); yield break; } HoldDependRes(); State = ResState.Loading; var abQ = abR.AssetBundle.LoadAssetAsync(mAssetName); mAssetBundleRequest = abQ; yield return(abQ); mAssetBundleRequest = null; UnHoldDependRes(); if (!abQ.isDone) { Log.E("Failed Load Asset:" + mAssetName); OnResLoadFaild(); finishCallback(); yield break; } mAsset = abQ.asset; } State = ResState.Ready; finishCallback(); }
public static IEnumerator AssetBundleRequest(SimpleCoroutineAwaiter <Object> awaiter, AssetBundleRequest instruction) { yield return(instruction); awaiter.Complete(instruction.asset, null); }
/// <summary> /// 异步加载资源 /// </summary> /// <param name="assetName">资源名称</param> public void LoadAssetAsync <T>(string assetBundleName, string assetName, Action <string, UnityEngine.Object> asyncCallback) where T : Object { assetName = assetName.ToLower(); AssetBundle assetBundle; if (!_allAssets.TryGetValue(assetName, out assetBundle)) { string assetBundlePath = Path.Combine(_readPath, assetBundleName); try { //异步加载assetbundle AssetBundleCreateRequest createRequest = LoadAssetBundleAsync(assetBundlePath); createRequest.completed += (operation) => { assetBundle = createRequest.assetBundle; //存储资源名称 string[] assetNames = assetBundle.GetAllAssetNames(); if (assetBundle.isStreamedSceneAssetBundle) { assetNames = assetBundle.GetAllScenePaths(); } foreach (var name in assetNames) { if (!_allAssets.ContainsKey(name)) { _allAssets.Add(name, assetBundle); } } //存储assetbundle _allAssetBundles[assetName] = new KeyValuePair <AssetBundle, string[]>(assetBundle, assetNames); //加载依赖项 LoadDependenciesAssetBundel(assetBundleName); //assetbundle异步加载资源 AssetBundleRequest requetAsset = assetBundle.LoadAssetAsync <T>(assetName); requetAsset.completed += (asyncOperation) => { asyncCallback.Invoke(assetName, requetAsset.asset); }; }; } catch (GamekException ex) { asyncCallback.Invoke(assetName, null); Debug.LogError(ex.ToString()); } } else { //加载依赖项 LoadDependenciesAssetBundel(assetBundleName); //assetbundle异步加载资源 AssetBundleRequest requetAsset = assetBundle.LoadAssetAsync <T>(assetName); requetAsset.completed += (asyncOperation) => { asyncCallback.Invoke(assetName, requetAsset.asset); }; } }
/* * 新建一个用于打包assetbundle的dictionary,转换AssetBundleConfig.txt中的prefab信息为新的assetbundle关系 * 将 prefabName -->> prefabPath : AssetbundlePath * 改为 AssetbundlePath -->> prefabName : prefabPath : prefabPath ... * 一个assetbundle可能包含多个prefab * */ static void InitAssetBundleDict() { ResourceManager.Instance.Init (""); var _prefabDict = ResourceManager.Instance.PrefabRequestDict; foreach (var obj in _prefabDict) { var request = obj.Value; var assetbundlePath = request.AssetbundlePath; var prefabPath = request.PrefabPath; AssetBundleRequest assetbundleRequest = null; if (_assetBundleDict.TryGetValue(assetbundlePath, out assetbundleRequest)) { //assetbundlePath目录一致,则打到同一个assetbundle中 assetbundleRequest.PrefabList.Add(prefabPath); } else { assetbundleRequest = new AssetBundleRequest(); assetbundleRequest.Name = request.PrefabName; assetbundleRequest.PrefabList = new List<string>(); assetbundleRequest.PrefabList.Add(prefabPath); assetbundleRequest.IsShared = false; _assetBundleDict.Add(assetbundlePath, assetbundleRequest); } } var sharedDict = ResourceManager.Instance.SharedAssetbundleDict; foreach(var obj in sharedDict) { var request = obj.Value; var assetbundlePath = request.AssetbundlePath; var prefabPath = request.PrefabPath; AssetBundleRequest assetbundleRequest = null; if (_assetBundleDict.TryGetValue(assetbundlePath, out assetbundleRequest)) { //assetbundlePath目录一致,则打到同一个assetbundle中 assetbundleRequest.PrefabList.Add(prefabPath); } else { assetbundleRequest = new AssetBundleRequest(); assetbundleRequest.Name = request.PrefabName; assetbundleRequest.PrefabList = new List<string>(); assetbundleRequest.PrefabList.Add(prefabPath); assetbundleRequest.IsShared = true; _assetBundleDict.Add(assetbundlePath, assetbundleRequest); } } }
private IEnumerator _Init(string path) { Object getAsset = null; { // 添加扩展名 string abPath = path; if (!abPath.EndsWith(GEngineDef.AssetBundleExt)) { abPath = abPath + GEngineDef.AssetBundleExt; } //if(abPath.StartsWith("avatar")) { //abPath = "avatar" + GEngineDef.AssetBundleExt; } if (abPath.IndexOf("kuijiabing_1_1") > 0) { abPath = "avatar/soldier/kuijiabing_1_1" + GEngineDef.AssetBundleExt; } else if (abPath.IndexOf("kuijiabing_1_2") > 0) { abPath = "avatar/soldier/kuijiabing_1_2" + GEngineDef.AssetBundleExt; } _bundleLoader = AssetBundleLoader.Load(abPath); while (!_bundleLoader.IsCompleted) { yield return(null); } if (!_bundleLoader.IsSuccess) { Debug.LogErrorFormat("[AssetLoader]Load BundleLoader Failed(Error) when Finished: {0}", path); //_bundleLoader.Release(); OnFinish(null); yield break; } var assetBundle = _bundleLoader.Bundle; DateTime beginTime = DateTime.Now; //var abAssetName = Path.GetFileNameWithoutExtension(Url).ToLower(); var abAssetName = AssetManager.GetAssetRelativePath(path); //Debug.Log("Try to load asset name: " + abAssetName); foreach (string name in assetBundle.GetAllAssetNames()) { //Debug.Log("------------------------------------>: " + name); } if (!assetBundle.isStreamedSceneAssetBundle) { AssetBundleRequest request = null; if (abAssetName.EndsWith(".png")) { request = assetBundle.LoadAssetAsync(abAssetName, typeof(Sprite)); } else { request = assetBundle.LoadAssetAsync(abAssetName); } //var request = assetBundle.LoadAssetAsync(abAssetName); while (!request.isDone) { yield return(null); } Debuger.Assert(getAsset = request.asset); //_bundleLoader.PushLoadedAsset(getAsset); // TODO: finish me } else { Debug.LogError("URL: " + Url + " --> isStreamedSceneAssetBundle"); // if it's a scene in asset bundle, did nothing // but set a fault Object the result //getAsset = KResourceModule.Instance; } ResourceModule.LogLoadTime("AssetLoader: load asset time: ", path, beginTime); if (getAsset == null) { Debug.LogErrorFormat("Asset is NULL: {0}", path); } } if (Application.isEditor && getAsset != null && getAsset is GameObject) { RefreshMaterialsShadersForEditorEnv(getAsset as GameObject); //if (getAsset != null) // KResoourceLoadedAssetDebugger.Create(getAsset.GetType().Name, Url, getAsset as Object); } if (getAsset != null) { // 更名~ 注明来源asset bundle 带有类型 //getAsset.name = String.Format("{0}~{1}", getAsset, Url); } OnFinish(getAsset); }
private IEnumerator LoadAllNeedAsset() { /// 新建资源库 if (m_mapObject == null) { m_mapObject = new Dictionary <string, Object>(); } else { yield break; } m_progress = 0f; int nAssetBundlesCount = routePath.Length; for (int i = 0; i < nAssetBundlesCount; i++) { int nAssetBundleType = getAssetBundleType(routePath[i]); AssetBundle assetBundle = SimpleFramework.LuaHelper.GetResManager().LoadAssetBundle(routePath[i]); if (/*nAssetBundleType == (int)AssetBundleType.Shoal || */ nAssetBundleType == (int)AssetBundleType.None) { m_progress += resourceWeight[nAssetBundleType]; //Debuger.Log(string.Format("Asset Name = {0}, nAssetBundlesCount = {1}", abs[i], nAssetBundleType)); yield return(null); continue; } else { m_progress += resourceWeight[nAssetBundleType] * 0.1f; } string[] szAssetNames = assetBundle.GetAllAssetNames(); int nAssetCount = szAssetNames.Length; for (int j = 0; j < nAssetCount; j++) { string szAssetName = szAssetNames[j]; //Debuger.Log(string.Format("Loading Asset Name = {0}", szAssetName)); string key; string assetprefix = szAssetPrefix.ToLower(); if (szAssetName.StartsWith(assetprefix)) { key = szAssetName.Substring(assetprefix.Length); } else { key = szAssetName; } if (m_mapObject.ContainsKey(key)) { Debug.LogError(string.Format("{0} has already exists in ResourceManager", key)); continue; } m_progress += ((float)1 / nAssetCount) * resourceWeight[nAssetBundleType] * 0.9f; AssetBundleRequest request = assetBundle.LoadAssetAsync(szAssetName); yield return(request); Object o = request.asset; m_mapObject.Add(key, o); } assetBundle.Unload(false); } m_progress = 1.0f; }
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; _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); if (_ExpectedObjectReferenceCount != 0) { #if UNITY_EDITOR if (!_UsingBundles) { var resourceRequests = UnityEditorInternal.InternalEditorUtility.LoadSerializedFileAndForget(_ResourcesPathObjRefs); _ResourceObjRefs = (ReferencedUnityObjects)resourceRequests[0]; _LoadingStatus = LoadingStatus.WaitingForResourcesLoad; } else #endif if (_ResourceObjRefs != null) { _LoadingStatus = LoadingStatus.WaitingForResourcesLoad; } else { if (!_BlockUntilFullyLoaded) { _AssetBundleRequest = AssetBundle.LoadFromFileAsync(_ResourcesPathObjRefs); } else { _AssetBundle = AssetBundle.LoadFromFile(_ResourcesPathObjRefs); } _LoadingStatus = LoadingStatus.WaitingForAssetBundleLoad; } } else { _LoadingStatus = LoadingStatus.WaitingForEntitiesLoad; } } 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 (!_BlockUntilFullyLoaded) { 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; } else { _ResourceObjRefs = _AssetBundle.LoadAsset <ReferencedUnityObjects>(Path.GetFileName(_ResourcesPathObjRefs)); _LoadingStatus = LoadingStatus.WaitingForEntitiesLoad; } } // 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); if (_BlockUntilFullyLoaded) { _EntityManager.ExclusiveEntityTransactionDependency.Complete(); } } 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}"); } } }
public IEnumerator loadModel() { WWW www = new WWW(ModelURL); //WWW www = WWW.LoadFromCacheOrDownload(ModelURL,0); yield return(www); if (www.error == null) { AssetBundle bundle = www.assetBundle; AssetBundleRequest request = bundle.LoadAssetAsync(ModelName, typeof(GameObject)); yield return(request); //GameObject go = request.asset as GameObject; GameObject go = Instantiate(request.asset) as GameObject; //GameObject parent = GameObject.Find("GameObject"); //go.transform.SetParent(parent.transform); //Debug.Log("CommonAvatar:" + (commonHumanAvatar.isHuman ? "is human" : "is generic")); //RigBoneMapping. //HumanPoseHandler.SetHumanPose(HumanPose) //HumanDescription humDes = new HumanDescription(); //go.transform.parent = null; //go.transform.position = Vector3.zero; //go.transform.rotation = Quaternion.identity; //HumanDescription humDes = CreateHumanDescription(go); //Avatar avatar = AvatarBuilder.BuildHumanAvatar(go, humDes); //Avatar avatar = AvatarBuilder.BuildGenericAvatar(go, ""); //avatar.name = "avatar"; //Debug.Log(avatar.isHuman ? "is human" : "is generic"); //Avatar avatar = CreateAvatar(go); go.transform.localScale = new Vector3(100, 100, 100); Animator animator = go.GetComponent <Animator>() as Animator; //animator.GetBoneTransform(HumanBodyBones.) //animator.InterruptMatchTarget(); //animator.avatar = avatar; //animator.avatar = commonHumanAvatar; animator.runtimeAnimatorController = animatorController; go.transform.localScale = new Vector3(100, 100, 100); //animator.Play("RoundKick"); //animator.Play("Walk"); animator.Play("Run"); //animator.Play("Idle"); } else { Debug.Log(www.error); } }
public static UniTask <UnityEngine.Object> WithCancellation(this AssetBundleRequest asyncOperation, CancellationToken cancellationToken) { return(ToUniTask(asyncOperation, cancellationToken: cancellationToken)); }
IEnumerator AnalyzXml(string strXml) { //存在 XmlDocument doc = new XmlDocument(); doc.Load(strXml); XmlElement root = doc.DocumentElement;//doc.SelectSingleNode("root"); if (root != null) { //nodelist XmlNodeList scenelist = root.SelectNodes("scene"); foreach (XmlNode scene in scenelist) { foreach (XmlNode gameobj in scene.ChildNodes) { XmlElement obj = (XmlElement)gameobj; if (obj != null) { string objname = obj.GetAttribute("objectName"); string perfab = obj.GetAttribute("objectAsset"); Vector3 pos = Vector3.zero; Vector3 scale = Vector3.zero; Vector3 rotate = Vector3.zero; //trans XmlNodeList trans = obj.SelectSingleNode("transform").ChildNodes; foreach (XmlElement prs in trans) { if (prs.Name == "position") { // string x = prs["position"]["x"].InnerText; foreach (XmlElement position in prs.ChildNodes) { switch (position.Name) { case "x": pos.x = float.Parse(position.InnerText); break; case "y": pos.y = float.Parse(position.InnerText); break; case "z": pos.z = float.Parse(position.InnerText); break; } } } else if (prs.Name == "rotation") { foreach (XmlElement rotation in prs.ChildNodes) { switch (rotation.Name) { case "x": rotate.x = float.Parse(rotation.InnerText); break; case "y": rotate.y = float.Parse(rotation.InnerText); break; case "z": rotate.z = float.Parse(rotation.InnerText); break; } } } else if (prs.Name == "scale") { foreach (XmlElement sca in prs.ChildNodes) { switch (sca.Name) { case "x": scale.x = float.Parse(sca.InnerText); break; case "y": scale.y = float.Parse(sca.InnerText); break; case "z": scale.z = float.Parse(sca.InnerText); break; } } } else { continue; } } perfab = perfab.Replace(".prefab", ".assetbundle"); Object perfabobj = null;// Resources.LoadAssetAtPath("Assets/StreamingAssets/Perfab/" + perfab, typeof(GameObject)); //加载prefabs,CreateFromFile只适合在pc端使用 //AssetBundle bundle = AssetBundle.CreateFromFile(Application.streamingAssetsPath + @"/AssetBundle/" + perfab); //本地路径 //string url = Util.LocalUrl + @"/AssetBundle/" + perfab; //WWW www = new WWW(url); //yield return www; //AssetBundleRequest req = www.assetBundle.LoadAsync(perfab.Replace(".assetbundle",""), typeof(Object)); //while (req.isDone == false) // yield return null; //perfabobj = req.asset; string uri = Util.DataPath + @"/AssetBundle/" + perfab; UnityEngine.Debug.LogWarning("LoadFile::>> " + uri); byte[] stream = File.ReadAllBytes(uri); AssetBundle bundle = AssetBundle.CreateFromMemoryImmediate(stream); AssetBundleRequest req = bundle.LoadAsync(perfab.Replace(".assetbundle", ""), typeof(Object)); while (req.isDone == false) { yield return(null); } perfabobj = req.asset; //创建一个物体 GameObject ob = (GameObject)Instantiate(perfabobj, pos, Quaternion.Euler(rotate)); ob.transform.localScale = scale; Animation an = ob.GetComponent <Animation>(); if (an != null) { TitleCharacter.players.Add(ob); } //www.assetBundle.Unload(false); //www.Dispose(); } } } } }
// 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, Action complete = 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, complete)); yield break; } _handlers.Add(fullPath, new List <LoadHandlers> { new LoadHandlers(success, error, complete) }); _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.InvokeError(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.InvokeError(exception); } _handlers.Remove(fullPath); yield break; } assetBundleCreateRequest.assetBundle.Unload(false); try { var loadedAvatar = _container.Instantiate <LoadedAvatar>(new object[] { fullPath, (GameObject)assetBundleRequest.asset }); _logger.Info($"Successfully loaded avatar '{loadedAvatar.descriptor.name}' by '{loadedAvatar.descriptor.author}' from '{fullPath}'"); foreach (LoadHandlers handler in _handlers[fullPath]) { handler.InvokeSuccess(loadedAvatar); } } catch (Exception ex) { _logger.Error($"Failed to load avatar at '{fullPath}'"); _logger.Error(ex); foreach (LoadHandlers handler in _handlers[fullPath]) { handler.InvokeError(new AvatarLoadException("Failed to load avatar", ex)); } } _handlers.Remove(fullPath); }
public LoadingAsset(string bundleName, string assetName, AssetBundleRequest assetBundleRequest) : base(bundleName, new AssetKey(typeof(T), assetName), assetBundleRequest) { }
internal override void Unload() { _request = null; loadState = LoadState.Unload; base.Unload(); }
public AssetBundleRequestAllAssetsAwaiter(AssetBundleRequest asyncOperation) { this.asyncOperation = asyncOperation; this.continuationAction = null; }
public static AssetBundleRequestAwaiter GetAwaiter(this AssetBundleRequest resourceRequest) { Error.ThrowArgumentNullException(resourceRequest, nameof(resourceRequest)); return(new AssetBundleRequestAwaiter(resourceRequest)); }
public AssetManagerRequest(ResourceRequest resReq, AssetBundleRequest assReq) { this._resReq = resReq; this._assReq = assReq; }
public static UniTask <UnityEngine.Object> ToUniTask(this AssetBundleRequest resourceRequest) { Error.ThrowArgumentNullException(resourceRequest, nameof(resourceRequest)); return(new UniTask <UnityEngine.Object>(new AssetBundleRequestAwaiter(resourceRequest))); }
//异步加载协程 IEnumerator AsyncLoadCor() { //回调队列 List <AsyncLoadResCallBackInfo> callBackList = null; long lastYieldTime = System.DateTime.Now.Ticks; while (true) { bool haveYield = false; //遍历需加载资源队列 for (int i = 0; i < (int)LoadResPriority.RES_NUM; i++) { List <AsyncLoadResInfo> loadingList = m_LoadingAssetList[i]; if (loadingList.Count <= 0) { continue; } AsyncLoadResInfo loadingItem = loadingList[0]; loadingList.RemoveAt(0); //取出回调 callBackList = loadingItem.m_CallBackList; Object obj = null; ResourceItem item = null; #if UNITY_EDITOR if (!m_loadFromAssetBundle) { obj = LoadAssetByEditor <Object>(loadingItem.m_Path); //模拟异步加载 yield return(new WaitForSeconds(0.5f)); item = AssetBundleMgr.Instance.GetResourceItem(loadingItem.m_Crc); } #endif if (obj == null) { item = AssetBundleMgr.Instance.LoadResourceAssetBundle(loadingItem.m_Crc); if (item != null && item.m_AssetBundle != null) { AssetBundleRequest abRequest = null; if (loadingItem.isSprite) { abRequest = item.m_AssetBundle.LoadAssetAsync <Sprite>(item.m_AssetName); } else { abRequest = item.m_AssetBundle.LoadAssetAsync(item.m_AssetName); } yield return(abRequest); if (abRequest.isDone) { obj = abRequest.asset; } lastYieldTime = System.DateTime.Now.Ticks; } } CacheResource(loadingItem.m_Path, ref item, loadingItem.m_Crc, obj, callBackList.Count); for (int j = 0; j < callBackList.Count; j++) { AsyncLoadResCallBackInfo callBack = callBackList[j]; if (callBack != null && callBack.m_DealFinish != null) { callBack.m_DealFinish(loadingItem.m_Path, obj, callBack.m_Param1, callBack.m_Param2, callBack.m_Param3);//执行回调 callBack.m_DealFinish = null; } callBack.Reset(); m_AsyncCallBackPool.Recycle(callBack); } obj = null; callBackList.Clear(); m_LoadingAssetDic.Remove(loadingItem.m_Crc); loadingItem.Reset(); m_AsyncLoadResParamPool.Recycle(loadingItem); if (System.DateTime.Now.Ticks - lastYieldTime > MAXLOADRESTIME)//大于这个时间等待一帧 { yield return(null); lastYieldTime = System.DateTime.Now.Ticks; haveYield = true; } } if (!haveYield || System.DateTime.Now.Ticks - lastYieldTime > MAXLOADRESTIME)//大于这个时间等待一帧 { lastYieldTime = System.DateTime.Now.Ticks; } yield return(null); } }
private ETTask InnerLoadAllAssetsAsync() { this.tcs = new ETTaskCompletionSource(); this.request = assetBundle.LoadAllAssetsAsync(); return(this.tcs.Task); }
private IEnumerator CoLoad() { ready = false; curIndex = 0; totalIndex = 0; foreach (var des in loadingDict.Values) { totalIndex += Manifest.GetAllDependencies(des.AssetBundleTag).Length; totalIndex += 1; } foreach (var des in loadingDict.Values) { //异步加载所有依赖 string[] dependencies = Manifest.GetAllDependencies(des.AssetBundleTag); Dictionary <string, AssetBundleCreateRequest> array = new Dictionary <string, AssetBundleCreateRequest>(); int index = 0; foreach (string str in dependencies) { string fullPath = Config.AssetPath + str.Substring(4); AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(fullPath); array.Add(str, request); index++; } //等待依赖加载完成 foreach (var obj in array.Values) { yield return(obj); curIndex++; } //异步加载目标AssetBundle AssetBundleCreateRequest re = AssetBundle.LoadFromFileAsync(des.FullPath); array.Add(des.RelativePath.ToLower(), re); yield return(re); curIndex++; //从目标AssetBundle中异步加载资源 AssetBundleRequest abre = re.assetBundle.LoadAssetAsync(des.AssetName, GameUtil.GetAssetType(des.AssetType)); yield return(abre); des.Asset = abre.asset; //添加资源到缓存 if (!cacheDict.ContainsKey(des.RelativePath)) { cacheDict.Add(des.RelativePath, des.Asset); } //发布加载结束回调 if (callbackDict[des.RelativePath] == null || callbackDict[des.RelativePath].Count <= 0) { Debug.LogError("loaded asset'callback is none"); yield break; } foreach (var callback in callbackDict[des.RelativePath]) { callback(des.Asset); } callbackDict[des.RelativePath] = new System.Collections.Generic.List <Action <object> >(); foreach (var t in array) { t.Value.assetBundle.Unload(false); } } loadingDict = new Dictionary <string, AssetDesc>(); ready = true; }
protected override void OnUnload() { base.OnUnload(); assetBundleRequest = null; loadState = 0; }
public static bool LoadAsync <T>(string path, out AssetBundleRequest request) where T : UnityEngine.Object { return(LoadAsync(path, typeof(T), out request)); }
public AssetRequest(AssetBundleRequest request) { this.request = request; }
public CharacterRequest(string name, Bundle bundle) { gameObjectRequest = bundle.LoadAssetAsync("rendererobject", typeof(GameObject)); materialRequest = bundle.LoadAssetAsync(name, typeof(Material)); boneNameRequest = bundle.LoadAssetAsync("bonenames", typeof(StringHolder)); }