///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// 加载基础部件完成 /// </summary> public void onLoadBaseElementComplete() { string strUrl = createBaseURL(); _baseAssetbundleLoadTask = new AssetBundleLoadTask(strUrl); _baseAssetbundleLoadTask.EventFinished += new task.TaskBase.FinishedHandler(delegate(bool manual, TaskBase currentTask) { _bothLoadComplete.ConditionOK(2, bothLoadComplete); }); /* * FileStream fs = new FileStream(Application.dataPath + "/" + strUrl, FileMode.Open, FileAccess.Read); * if (fs != null) * { * byte[] content = new byte[fs.Length]; * fs.Read(content, 0, content.Length); * fs.Close(); * * AssetBundle baseAdb = AssetBundle.CreateFromMemoryImmediate(content); * * GameObject objBase = baseAdb.mainAsset as GameObject; * * //基础对象 * _pModelRoot = (GameObject)UnityEngine.Object.Instantiate(objBase); * _pModelRoot.name = _strModelName; * * //删除assetbundle镜像 * baseAdb.Unload(false); * _bIsBaseLoaded = true; * } * */ }
//获取依赖文件任务; private void GetDependsTask(string varAssetFileName) { string[] tempDepends = ResourceManager.GetManager().GetAssetBundleDepends(varAssetFileName); if (tempDepends != null && tempDepends.Length > 0) { if (mDependList == null) { mDependList = new List <ResourceLoadTask>(); } for (int i = 0; i < tempDepends.Length; i++) { string tempDependRes = tempDepends[i]; tempDependRes = tempDependRes.ToLower(); //GetDependsTask(tempDependRes); ResourceLoadTask tempTask = ResourceManager.GetManager().GetResourceLoadTask(tempDependRes); if (tempTask == null) { tempTask = new AssetBundleLoadTask(tempDependRes, null, null, null, null); mDependList.Add(tempTask); } } } }
private IEnumerator doLoadAssetBunlde(AssetBundleLoadTask bundleTask) { // 需要等待缓存准备好 while (!Caching.ready) { yield return(null); } // 有相同版本号的AssetBundle就从缓存中获取,否则下载进缓存。 WWW www = new WWW(bundleTask.path); yield return(www); if (www.error != null) { throw new Exception("WWW download had an error:" + www.error); } bundleTask.state = AssetLoadState.E_LOADED; bundleTask.bundle = www.assetBundle; //加载asset foreach (KeyValuePair <string, AssetLoadTask> kvp in bundleTask.assetReqDic) { kvp.Value.state = AssetLoadState.E_LOADING; StartCoroutine(doLoadAsset(kvp.Key, bundleTask)); } }
/// <summary> /// 异步加载资源 /// handlerFinish:结束回调 /// </summary> public void loadAssetAsync(string strAssetPath, task.TaskBase.FinishedHandler handlerFinish = null) { if (!isAssetbundleLoaded(strAssetPath)) { if (AssetManager.getInstance().IsStreamingAssets(strAssetPath)) { //异步创建StreamingAssets下资源 strAssetPath = UtilTools.PathCheck(strAssetPath); AssetBundleLoadTask task = new AssetBundleLoadTask(strAssetPath, null); if (handlerFinish != null) { task.EventFinished += handlerFinish; } } else { AssetLoadTask task = new AssetLoadTask(strAssetPath, null); if (handlerFinish != null) { task.EventFinished += handlerFinish; } } } else { if (AssetManager.getInstance().IsStreamingAssets(strAssetPath)) { strAssetPath = UtilTools.PathCheck(strAssetPath); } AssetManager.getInstance().addAssetbundleRefCount(strAssetPath); StartCoroutine("loadAssetAsyncCallback", handlerFinish); } }
/// <summary> /// Unload asset bundle. /// </summary> /// <param name="assetBundleName">Asset bundle name.</param> public static void UnLoadAssetBundle(string assetBundleName) { #if UNITY_EDITOR // If we're in Editor simulation mode, we don't have to load the manifest assetBundle. if (SimulateAssetBundleInEditor) { return; } #endif if (m_PresaveAssetBundleNames.Contains(assetBundleName)) { return; } string[] dependencies = null; m_Dependencies.TryGetValue(assetBundleName, out dependencies); if (dependencies != null) { int length = dependencies.Length; string depend = ""; for (int i = 0; i < length; i++) { depend = dependencies[i]; UnLoadAssetBundle(depend); } } string error; LoadedAssetBundle bundle = GetLoadedAssetBundle(assetBundleName, out error); if (bundle != null) { if (--bundle.referencedCount == 0) { bundle.assetBundle.Unload(true); m_LoadedAssetBundles.Remove(assetBundleName); m_Dependencies.Remove(assetBundleName); DebugLogger.LogFormat("[AssetLoadManager]:{0} has been unloaded successfully", assetBundleName); } return; } AssetBundleLoadTask loadTask = null; if (m_LoadAssetBundleTasks.TryGetValue(assetBundleName, out loadTask)) { if (--loadTask.referencedCount == 0) { m_LoadAssetBundleTasks.Remove(assetBundleName); } } }
public void loadLocalAssetAsync(string assetBundleName, string assetName, Action <AssetBundleRequest> loadCB) { string assetBundlePath = StreamingAssetPath + "AssetBundles/" + assetBundleName; //string assetBundlePath = "http://www.vmetu.com/external/res/buttons"; Debug.Log("Asset:" + assetBundlePath); AssetBundleLoadTask bundleTask = null; if (_assetBundleDic.ContainsKey(assetBundlePath)) { bundleTask = _assetBundleDic[assetBundlePath]; } else { bundleTask = new AssetBundleLoadTask { path = assetBundlePath, state = AssetLoadState.E_NONE }; _assetBundleDic.Add(assetBundlePath, bundleTask); } AssetLoadTask assetLoadTask = bundleTask.getOrCreateAssetLoadTask(assetName); switch (bundleTask.state) { case AssetLoadState.E_NONE: //还没开始加载 bundleTask.state = AssetLoadState.E_LOADING; assetLoadTask.loadedCb += loadCB; StartCoroutine(doLoadAssetBunlde(bundleTask)); break; case AssetLoadState.E_LOADING: //下载中,把回调加入到响应的回调中 { assetLoadTask.loadedCb += loadCB; } break; case AssetLoadState.E_LOADED: //assetBundle已下载完成 { if (assetLoadTask.state == AssetLoadState.E_LOADED) { loadCB(assetLoadTask.assetBundleRequest); } else if (assetLoadTask.state == AssetLoadState.E_LOADED) { assetLoadTask.loadedCb += loadCB; } else { StartCoroutine(doLoadAsset(assetName, bundleTask)); } } break; } }
//show win public bool CreateWin(int iDepth, bool byAction) { IsClose = false; if (_isLoading || _isShow) { return(false); } windDepth = iDepth; _isLoading = true; _isShow = true; isCreateByAction = byAction; ClearAllCacheEvent(); _loadResTaskList.Clear(); _loadCompleteList.Clear(); string[] appendPrefabs = GetAppendAtlasPrefabs(); if (appendPrefabs.Length > 0) { for (int i = 0; i < appendPrefabs.Length; i++) { if (AssetManager.getInstance().IsStreamingAssets(appendPrefabs[i])) { //转为assetbundle路径 appendPrefabs[i] = UtilTools.PathCheck(appendPrefabs[i]); //加载StreamingAssets下资源 AssetBundleLoadTask task = new AssetBundleLoadTask(appendPrefabs[i]); _loadResTaskList.Add(task); task.EventFinished += (manual, currentTask) => { LoadAppendResourceComplete(currentTask._taskName); }; } else { //加载Resources下资源 AssetLoadTask task = new AssetLoadTask(appendPrefabs[i]); _loadResTaskList.Add(task); task.EventFinished += (manual, currentTask) => { LoadAppendResourceComplete(currentTask._taskName); }; } } } else { LoadAppendResourceComplete(""); } UILoadCallback(); return(true); }
/// <summary> /// 加载资源的方法; /// </summary> /// <param name="AssetFileName"></param> /// <param name="AssetObjectName"></param> /// <param name="AssetObjectType"></param> /// <param name="callback"></param> /// <param name="varParam"></param> /// <returns></returns> public bool LoadAssetBundle(string AssetFileName, string AssetObjectName, Type AssetObjectType, ResourceLoadCallback callback = null, object varParam = null) { ResourceLoadTask tempTask = null; if (mResourcesModel == ResourcesModel.RM_Resources) { tempTask = new EditorResourceLoadTask(AssetFileName, AssetObjectName, AssetObjectType, callback, varParam); } else { AssetFileName = AssetFileName.ToLower(); tempTask = new AssetBundleLoadTask(AssetFileName, AssetObjectName, AssetObjectType, callback, varParam); } mLoadtasks.Enqueue(tempTask); return(true); }
/// <summary> /// 初始化Asset模块 /// </summary> public void intialize() { #if UNITY_STANDALONE || UNITY_EDITOR if (_objPathData == null) { _objPathData = new StandalonePath(); } #elif UNITY_IPHONE //_isFirstUseStreamingAssets = true; if (_objPathData == null) { _objPathData = new iOSPath(); } #elif UNITY_ANDROID //_isFirstUseStreamingAssets = true; if (_objPathData == null) { _objPathData = new AndroidPath(); } #endif if (_mainfest == null && !_bIniting) { _bIniting = true; //加载StreamingAssets下资源 // if (_isFirstUseStreamingAssets) // { AssetBundleLoadTask task = new AssetBundleLoadTask(IPath.getPlatformName()); task.EventFinished += (manual, currentTask) => { AssetBundle assetObj = ((AssetBundleLoadTask)currentTask).getTargetAssetbundle(); if (assetObj != null) //assetObj为窗口的prefab { _mainfest = (AssetBundleManifest)assetObj.LoadAsset("AssetBundleManifest"); _bIniting = false; removeAssetbundle(currentTask._taskName); } }; //} } // GameObject ui_root = GameObject.Find("UIRoot"); // LoadManifest loader = ui_root.AddComponent<LoadManifest>(); // loader.assetBundlePath = "file:///" + IPath.streamingAssetsPathPlatform() + "/" + IPath.getPlatformName();// +".manifest"; // loader.completeCallback = manifestLoadComplete; }
private IEnumerator doLoadAsset(string name, AssetBundleLoadTask assetBundleLoadTask) { AssetLoadTask assetLoadTask = assetBundleLoadTask.getOrCreateAssetLoadTask(name); // 异步加载 assetLoadTask.assetBundleRequest = assetBundleLoadTask.bundle.LoadAssetAsync(name); // 等待加载完成 yield return(assetLoadTask.assetBundleRequest); assetLoadTask.state = AssetLoadState.E_LOADED; if (assetLoadTask.loadedCb != null) { assetLoadTask.loadedCb(assetLoadTask.assetBundleRequest); } assetLoadTask.loadedCb = null; }
public void LoadAppendResourceComplete(string path) { if (!string.IsNullOrEmpty(path)) { _loadCompleteList.Add(path); } if (_loadCompleteList.Count >= _loadResTaskList.Count)//依赖资源加载完后加载界面 { if (AssetManager.getInstance().IsStreamingAssets(prefabsPath[0])) { //转为assetbundle路径 prefabsPath[0] = UtilTools.PathCheck(prefabsPath[0]); //加载StreamingAssets下资源 AssetBundleLoadTask task = new AssetBundleLoadTask(prefabsPath[0]); _loadResTaskList.Add(task); task.EventFinished += (manual, currentTask) => { Object assetObj = ((AssetBundleLoadTask)currentTask).getTargetAsset(); if (assetObj != null) //assetObj为窗口的prefab { LoadResourceComplete(assetObj); //AssetManager.getInstance().removeAssetbundle(prefabsPath[0]); } }; } else { //加载Resources下资源 AssetLoadTask task = new AssetLoadTask(prefabsPath[0]); _loadResTaskList.Add(task); task.EventFinished += (manual, currentTask) => { Object assetObj = ((AssetLoadTask)currentTask).getTargetAsset(); if (assetObj != null) //assetObj为窗口的prefab { LoadResourceComplete(assetObj); assetObj = null; //AssetManager.getInstance().removeAssetbundle(prefabsPath[0]); } }; } } }
/// <summary> /// Checks all dependencies loaded. /// </summary> /// <returns><c>true</c>, if all dependencies loaded was checked, <c>false</c> otherwise.</returns> /// <param name="task">Task.</param> private static bool CheckAllDependenciesLoaded(AssetBundleLoadTask task) { if (task.dependencies == null || task.dependencies.Length == 0) { return(true); } bool ok = true; for (int i = 0; i < task.dependencies.Length; i++) { if (m_LoadAssetBundleTasks.ContainsKey(task.dependencies[i])) { ok = false; break; } } return(ok); }
/// <summary> /// 实例化2 /// appendedAssets:指定额外的特殊依赖项 /// </summary> public void Instantiate(string strAssetPath, Vector3 position, Quaternion rotation, InitiateHandler handlerFinish, string[] appendedAssets = null) { //string strLatesVersionpath = _objPathData.getLatestVersionPath(strPath); Utils.LogSys.Log("AssetManager Get Path Data 5:" + strAssetPath); EAssetPathType eType = _objPathData.getAssetPathType(strAssetPath); if (eType == EAssetPathType.eResources)//异步创建Resource下资源 { AssetLoadTask task = new AssetLoadTask(strAssetPath, appendedAssets); task.EventFinished += new task.TaskBase.FinishedHandler(delegate(bool manual, TaskBase currentTask) { Object assetObj = ((AssetLoadTask)currentTask).getTargetAsset(); if (assetObj != null) { GameObject obj = GameObject.Instantiate(assetObj, position, rotation) as GameObject; ((AssetLoadTask)currentTask).unloadUnusedAssetbundle(false); handlerFinish(obj); } }); } else { //异步创建StreamingAssets下资源 AssetBundleLoadTask task = new AssetBundleLoadTask(strAssetPath, appendedAssets); task.EventFinished += new task.TaskBase.FinishedHandler(delegate(bool manual, TaskBase currentTask) { Object assetObj = ((AssetBundleLoadTask)currentTask).getTargetAsset(); if (assetObj != null) { GameObject obj = GameObject.Instantiate(assetObj, position, rotation) as GameObject; ((AssetBundleLoadTask)currentTask).unloadUnusedAssetbundle(false); handlerFinish(obj); } }); } }
/////////////////////////////////////////////////////////////////////////////////// public EffectObject(string strEffectName, bool bAutoDestroy = true, EEffectBehaviour eBehaviour = EEffectBehaviour.eDefault) { _eBehavourType = eBehaviour; _effectName = strEffectName; _bIsAutoDestroy = bAutoDestroy; EffectManager.getInstance().addList(this); // string strEffectPath = EffectManager.getEffectFilePath(_effectName); // if (strEffectName.Contains("Effects/")) { // strEffectPath = _effectName.Substring(0, _effectName.LastIndexOf('.')); // } if (!strEffectName.Contains("Effects/") && !strEffectName.Contains("effect/"))//“Effects/”下才是光效 { return; } //if (AssetManager.getInstance().IsFirstUseStreamingAssets) if (AssetManager.getInstance().IsStreamingAssets(_effectName)) { _loading = true; //加载StreamingAssets下资源 _effectName = UtilTools.PathCheck(_effectName); AssetBundleLoadTask task = new AssetBundleLoadTask(_effectName); task.EventFinished += (manual, currentTask) => { _loading = false; AssetManager.getInstance().minusAssetbundleRefCount(_effectName); if (_bDestroy) { return; } Object assetObj = ((AssetBundleLoadTask)currentTask).getTargetAsset(); if (assetObj == null) { return; } _effectGameObj = UnityEngine.Object.Instantiate(assetObj) as GameObject; if (_effectGameObj == null) { //Utils.LogSys.Log("Effect game object is NULL"); return; } UtilTools.UpdateShaders(_effectGameObj); InitEffect(); if (_loadComplete != null) { _loadComplete(this); } }; } else { /* * string strEffectPath = _effectName;// EffectManager.getEffectFilePath(_effectName); * if (strEffectName.Contains("Effects/"))//“Effects/”下才是光效 * { * strEffectPath = _effectName.Substring(0, _effectName.LastIndexOf('.')); * if (strEffectPath.IndexOf("Resources/") == 0)//有“Resources/”就去掉 * { * strEffectPath = strEffectPath.Substring(10); * } * * UnityEngine.Object objRes = Resources.Load(strEffectPath); * if (objRes) * { * _effectGameObj = UnityEngine.Object.Instantiate(objRes) as GameObject; * if (_effectGameObj == null) * { * Utils.LogSys.Log("Effect game object is NULL"); * return; * } * InitEffect(); * if (_loadComplete != null) * _loadComplete(this); * } * }*/ _loading = true; AssetManager.getInstance().loadAssetAsync(_effectName, (bool manual, TaskBase currentTask) => { _loading = false; AssetManager.getInstance().minusAssetbundleRefCount(_effectName); if (_bDestroy) { return; } Object assetObj = AssetManager.getInstance().getAsset(_effectName); if (assetObj == null) { return; } _effectGameObj = UnityEngine.Object.Instantiate(assetObj) as GameObject; if (_effectGameObj == null) { //Utils.LogSys.Log("Effect game object is NULL"); return; } UtilTools.UpdateShaders(_effectGameObj); InitEffect(); if (_loadComplete != null) { _loadComplete(this); } }); } }
void Update() { // Collect all the finished WWWs. m_keysToRemove.Clear(); foreach (var keyValue in m_LoadAssetBundleTasks) { AssetBundleLoadTask loadTask = keyValue.Value; if (loadTask.request == null) { if (CheckAllDependenciesLoaded(loadTask)) { string url = Utility.GetAssetBundleDiskPath(loadTask.assetBundleName); loadTask.request = AssetBundle.LoadFromFileAsync(url); } } else { // If downloading succeeds. if (loadTask.request.isDone) { AssetBundle bundle = loadTask.request.assetBundle; if (bundle == null) { m_DownloadingErrors.Add(keyValue.Key, string.Format("[AssetLoadManager]:{0} is not a valid asset bundle.", keyValue.Key)); m_keysToRemove.Add(keyValue.Key); continue; } LoadedAssetBundle loadedAssetBundle = new LoadedAssetBundle(bundle); loadedAssetBundle.referencedCount = loadTask.referencedCount; m_LoadedAssetBundles.Add(keyValue.Key, loadedAssetBundle); m_keysToRemove.Add(keyValue.Key); } } } // Remove the finished WWWs. foreach (var key in m_keysToRemove) { AssetBundleLoadTask loadTask = m_LoadAssetBundleTasks[key]; m_LoadAssetBundleTasks.Remove(key); } m_keysToRemove.Clear(); // Update all in progress operations for (int i = 0; i < m_InProgressOperations.Count;) { if (!m_InProgressOperations[i].Update()) { m_InProgressOperations.RemoveAt(i); } else { i++; } } AssetLoadGC(); }
//加载完成 public void loadComplete() { AssetBundle elemtAbd = null; /* * string strFilePath = Application.dataPath + "/" + _strUrl; * * if (!File.Exists(strFilePath)) * { * return; * } * * FileStream fs = new FileStream(strFilePath, FileMode.Open, FileAccess.Read); * if (fs != null) * { * byte[] content = new byte[fs.Length]; * fs.Read(content, 0, content.Length); * fs.Close(); * * elemtAbd = AssetBundle.CreateFromMemoryImmediate(content); * } * * */ _task = new AssetBundleLoadTask(_strUrl); _task.EventFinished += new task.TaskBase.FinishedHandler(delegate(bool manual, TaskBase currentTask) { elemtAbd = ((AssetBundleLoadTask)currentTask).getTargetAssetbundle(); //模型 if (elemtAbd != null) { //实例化对象 GameObject goPrefab = elemtAbd.LoadAsset <GameObject>(_strName + ".prefab"); //goPrefab.GetComponent<Renderer>().sharedMaterial.shader = null; Object pObj = (Object)goPrefab; //elemtAbd.LoadAsset<GameObject>(_strName + ".prefab"); GameObject pGameObj = (GameObject)Object.Instantiate(goPrefab, new Vector3(10000f, 10000f, 10000f), Quaternion.identity); //材质信息 pGameObj.GetComponent <Renderer>().material = Resources.Load(_strMatUrl) as Material; //获取蒙皮信息 _smrInfo = (SkinnedMeshRenderer)pGameObj.GetComponent <Renderer>(); //骨骼信息 Object pBonesObj = (Object)elemtAbd.LoadAsset <StringHolder>(_strName + "bonenames.asset"); StringHolder strholder = (StringHolder)pBonesObj; _arrBones = strholder.content; //加载完成 _bIsLoaded = true; //完成 if (_pModel != null) { _pModel.elementLoadComplete(_strName); } ((AssetBundleLoadTask)currentTask).unloadUnusedAssetbundle(false); } }); }
/// <summary> /// 载入xml配置 /// </summary> public override void LoadXML() { string xmlPath = _configPath + _fileName; // Object assets = AssetManager.getInstance().loadXML(xmlPath);//同步加载XML // if (assets != null) { // ParseXML(assets.ToString()); // LogSys.Log("load config success :" + xmlPath); // } //if (AssetManager.getInstance().IsFirstUseStreamingAssets) if (AssetManager.getInstance().IsStreamingAssets(xmlPath)) { xmlPath = UtilTools.PathCheck(xmlPath); AssetBundleLoadTask task = new AssetBundleLoadTask(xmlPath, null); task.EventFinished += new task.TaskBase.FinishedHandler(delegate(bool manual, TaskBase currentTask) { TextAsset assetObj = ((AssetBundleLoadTask)currentTask).getTargetAsset() as TextAsset; if (assetObj != null) { byte[] text_byte = assetObj.bytes; if (UtilTools.ArrayHeadIsWoDong(assetObj.bytes)) { CMyEncryptFile _encrypte = new CMyEncryptFile(); text_byte = _encrypte.Decrypt(assetObj.bytes, assetObj.bytes.Length); } ParseXML(text_byte); //LogSys.Log("load config success :" + xmlPath); } else { LogSys.LogError("load config failed:" + xmlPath); } _bLoadedXML = true; }); } else { AssetLoadTask task = new AssetLoadTask(xmlPath, null); task.EventFinished += new task.TaskBase.FinishedHandler(delegate(bool manual, TaskBase currentTask) { TextAsset assetObj = ((AssetLoadTask)currentTask).getTargetAsset() as TextAsset; if (assetObj != null) { byte[] text_byte = assetObj.bytes; if (UtilTools.ArrayHeadIsWoDong(assetObj.bytes)) { CMyEncryptFile _encrypte = new CMyEncryptFile(); text_byte = _encrypte.Decrypt(assetObj.bytes, assetObj.bytes.Length); } float start_time = Time.realtimeSinceStartup; ParseXML(text_byte); //Utils.LogSys.Log(string.Format("{0:0.00}", Time.realtimeSinceStartup - start_time) + " parse :" + currentTask._taskName); //LogSys.Log("load config success :" + xmlPath); } else { LogSys.LogError("load config failed:" + xmlPath); } _bLoadedXML = true; }); } }