Exemplo n.º 1
0
        protected override void OnBodyGUI()
        {
            base.OnBodyGUI();

            EventHandle();

            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();

            GUILayout.Label("Password:"******"";
            if (GUILayout.Button("Login", EditorStyles.miniButton))
            {
                _checkAction?.Invoke(_password);
                Close();
            }
            GUI.enabled = true;

            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.EndVertical();
        }
Exemplo n.º 2
0
 public override void OnRequestFinished(DownloadHandler handler)
 {
     if (handler == null)
     {
         Handler?.Invoke(null);
     }
     else
     {
         Handler?.Invoke(handler.text);
     }
 }
 public override void OnRequestFinished(DownloadHandler handler)
 {
     if (handler == null)
     {
         Handler?.Invoke(null);
     }
     else
     {
         DownloadHandlerTexture downloadHandler = handler as DownloadHandlerTexture;
         Handler?.Invoke(downloadHandler.texture);
     }
 }
 public override void OnRequestFinished(DownloadHandler handler)
 {
     if (handler == null)
     {
         Handler?.Invoke(null);
     }
     else
     {
         DownloadHandlerAudioClip downloadHandler = handler as DownloadHandlerAudioClip;
         Handler?.Invoke(downloadHandler.audioClip);
     }
 }
        /// <summary>
        /// 加载场景(异步)
        /// </summary>
        /// <param name="info">资源信息标记</param>
        /// <param name="loadingAction">加载中事件</param>
        /// <param name="loadDoneAction">加载完成事件</param>
        /// <returns>加载协程迭代器</returns>
        public IEnumerator LoadSceneAsync(SceneInfo info, HTFAction <float> loadingAction, HTFAction loadDoneAction)
        {
            float beginTime = Time.realtimeSinceStartup;

            //单线加载,如果其他地方在加载资源,则等待
            if (_isLoading)
            {
                yield return(_loadWait);
            }

            //轮到本线路加载资源
            _isLoading = true;

            //等待相关依赖资源的加载
            yield return(LoadDependenciesAssetBundleAsync(info.AssetBundleName));

            float waitTime = Time.realtimeSinceStartup;

            if (LoadMode == ResourceLoadMode.Resource)
            {
                throw new HTFrameworkException(HTFrameworkModule.Resource, "加载场景失败:场景加载不允许使用Resource模式!");
            }
            else
            {
#if UNITY_EDITOR
                if (IsEditorMode)
                {
                    LoadSceneParameters parameters = new LoadSceneParameters()
                    {
                        loadSceneMode    = LoadSceneMode.Additive,
                        localPhysicsMode = LocalPhysicsMode.None
                    };
                    yield return(EditorSceneManager.LoadSceneAsyncInPlayMode(info.AssetPath, parameters));
                }
                else
                {
                    yield return(LoadAssetBundleAsync(info.AssetBundleName, loadingAction));

                    yield return(SceneManager.LoadSceneAsync(info.ResourcePath, LoadSceneMode.Additive));
                }
#else
                yield return(LoadAssetBundleAsync(info.AssetBundleName, loadingAction));

                yield return(SceneManager.LoadSceneAsync(info.ResourcePath, LoadSceneMode.Additive));
#endif
            }

            float endTime = Time.realtimeSinceStartup;

            Log.Info(string.Format("异步加载场景完成[{0}模式]:{1}\r\n等待耗时:{2}秒  加载耗时:{3}秒"
                                   , LoadMode.ToString()
                                   , info.ResourcePath
                                   , waitTime - beginTime
                                   , endTime - waitTime));

            loadDoneAction?.Invoke();

            //本线路加载资源结束
            _isLoading = false;
        }
Exemplo n.º 6
0
        private static IEnumerator SynthesisByKEYCoroutine(string text, HTFAction <AudioClip> handler, int timeout, Speaker speaker, int volume, int speed, int pitch)
        {
            Tts tts = GetTts();

            tts.Timeout       = timeout;
            TtsOptions["spd"] = Mathf.Clamp(speed, 0, 9);
            TtsOptions["pit"] = Mathf.Clamp(pitch, 0, 9);
            TtsOptions["vol"] = Mathf.Clamp(volume, 0, 15);
            TtsOptions["per"] = (int)speaker;
            TtsOptions["aue"] = 6;
            TtsResponse response = tts.Synthesis(text, TtsOptions);

            yield return(response);

            if (response.Success)
            {
                AudioClip audioClip = SpeechUtility.ToAudioClip(response.Data);

                handler?.Invoke(audioClip);
            }
            else
            {
                GlobalTools.LogError("合成语音失败:" + response.ErrorCode + " " + response.ErrorMsg);
            }
            RecycleTts(tts);
        }
 /// <summary>
 /// 异步加载AB包(提供进度回调)
 /// </summary>
 /// <param name="assetBundleName">AB包名称</param>
 /// <param name="loadingAction">加载中事件</param>
 /// <param name="isManifest">是否是加载清单</param>
 /// <returns>协程迭代器</returns>
 private IEnumerator LoadAssetBundleAsync(string assetBundleName, HTFAction <float> loadingAction, bool isManifest = false)
 {
     if (!AssetBundles.ContainsKey(assetBundleName))
     {
         using (UnityWebRequest request = isManifest
             ? UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleRootPath + assetBundleName)
             : UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleRootPath + assetBundleName, GetAssetBundleHash(assetBundleName)))
         {
             request.SendWebRequest();
             while (!request.isDone)
             {
                 loadingAction?.Invoke(request.downloadProgress);
                 yield return(null);
             }
             if (!request.isNetworkError && !request.isHttpError)
             {
                 AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
                 if (bundle)
                 {
                     AssetBundles.Add(assetBundleName, bundle);
                 }
                 else
                 {
                     throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!");
                 }
             }
             else
             {
                 throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!");
             }
         }
     }
     yield return(null);
 }
Exemplo n.º 8
0
        /// <summary>
        /// 创建实体
        /// </summary>
        /// <param name="type">实体逻辑类</param>
        /// <param name="entityName">实体指定名称(为 <None> 时默认使用实体逻辑类名称)</param>
        /// <param name="loadingAction">创建实体过程进度回调</param>
        /// <param name="loadDoneAction">创建实体完成回调</param>
        /// <returns>加载协程</returns>
        public Coroutine CreateEntity(Type type, string entityName, HTFAction <float> loadingAction, HTFAction <EntityLogicBase> loadDoneAction)
        {
            EntityResourceAttribute attribute = type.GetCustomAttribute <EntityResourceAttribute>();

            if (attribute != null)
            {
                if (Entities.ContainsKey(type))
                {
                    if (attribute.IsUseObjectPool && ObjectPools[type].Count > 0)
                    {
                        EntityLogicBase entityLogic = GenerateEntity(type, ObjectPools[type].Dequeue(), entityName == "<None>" ? type.Name : entityName);

                        loadingAction?.Invoke(1);
                        loadDoneAction?.Invoke(entityLogic);
                        Main.m_Event.Throw(this, Main.m_ReferencePool.Spawn <EventCreateEntitySucceed>().Fill(entityLogic));
                        return(null);
                    }
                    else
                    {
                        if (_defineEntities.ContainsKey(type.FullName) && _defineEntities[type.FullName] != null)
                        {
                            EntityLogicBase entityLogic = GenerateEntity(type, Main.Clone(_defineEntities[type.FullName], _entitiesGroup[type].transform), entityName == "<None>" ? type.Name : entityName);

                            loadingAction?.Invoke(1);
                            loadDoneAction?.Invoke(entityLogic);
                            Main.m_Event.Throw(this, Main.m_ReferencePool.Spawn <EventCreateEntitySucceed>().Fill(entityLogic));
                            return(null);
                        }
                        else
                        {
                            return(Main.m_Resource.LoadPrefab(new PrefabInfo(attribute), _entitiesGroup[type].transform, loadingAction, (obj) =>
                            {
                                EntityLogicBase entityLogic = GenerateEntity(type, obj, entityName == "<None>" ? type.Name : entityName);

                                loadDoneAction?.Invoke(entityLogic);
                                Main.m_Event.Throw(this, Main.m_ReferencePool.Spawn <EventCreateEntitySucceed>().Fill(entityLogic));
                            }));
                        }
                    }
                }
                else
                {
                    throw new HTFrameworkException(HTFrameworkModule.Entity, "创建实体失败:实体对象 " + type.Name + " 并未存在!");
                }
            }
            return(null);
        }
Exemplo n.º 9
0
        //提取实体
        private Coroutine ExtractEntity(Type type, string entityName = "<None>", HTFAction <float> loadingAction = null, HTFAction <EntityLogicBase> loadDoneAction = null)
        {
            EntityResourceAttribute attribute = type.GetCustomAttribute <EntityResourceAttribute>();

            if (attribute != null)
            {
                if (_entities.ContainsKey(type))
                {
                    if (attribute.IsUseObjectPool && _objectPool[type].Count > 0)
                    {
                        EntityLogicBase entityLogic = Main.m_ReferencePool.Spawn(type) as EntityLogicBase;
                        _entities[type].Add(entityLogic);
                        entityLogic.Entity      = _objectPool[type].Dequeue();
                        entityLogic.Entity.name = entityLogic.Name = entityName == "<None>" ? type.Name : entityName;
                        entityLogic.Entity.SetActive(true);
                        entityLogic.OnInit();
                        entityLogic.OnShow();

                        loadingAction?.Invoke(1);
                        loadDoneAction?.Invoke(entityLogic);
                        Main.m_Event.Throw(this, Main.m_ReferencePool.Spawn <EventCreateEntitySucceed>().Fill(entityLogic));
                        return(null);
                    }
                    else
                    {
                        return(Main.m_Resource.LoadPrefab(new PrefabInfo(attribute), _entitiesGroup[type].transform, loadingAction, (obj) =>
                        {
                            EntityLogicBase entityLogic = Main.m_ReferencePool.Spawn(type) as EntityLogicBase;
                            _entities[type].Add(entityLogic);
                            entityLogic.Entity = obj;
                            entityLogic.Entity.name = entityLogic.Name = entityName == "<None>" ? type.Name : entityName;
                            entityLogic.Entity.SetActive(true);
                            entityLogic.OnInit();
                            entityLogic.OnShow();

                            loadDoneAction?.Invoke(entityLogic);
                            Main.m_Event.Throw(this, Main.m_ReferencePool.Spawn <EventCreateEntitySucceed>().Fill(entityLogic));
                        }));
                    }
                }
                else
                {
                    GlobalTools.LogError(string.Format("创建实体失败:实体对象 {0} 并未存在!", type.Name));
                }
            }
            return(null);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 完成任务点协程
        /// </summary>
        /// <param name="completeAction">完成后执行的操作</param>
        private IEnumerator CompleteCoroutine(HTFAction completeAction)
        {
            yield return(OnBeforeComplete());

            IsComplete = true;
            completeAction?.Invoke();
            Main.m_Event.Throw(this, Main.m_ReferencePool.Spawn <EventTaskPointComplete>().Fill(this, false));
        }
Exemplo n.º 11
0
        /// <summary>
        /// 回收对象
        /// </summary>
        /// <param name="obj">对象</param>
        public void Despawn(GameObject obj)
        {
            if (_objectQueue.Count >= _limit)
            {
                _onDespawn?.Invoke(obj);

                Main.Kill(obj);
            }
            else
            {
                obj.SetActive(false);

                _onDespawn?.Invoke(obj);

                _objectQueue.Enqueue(obj);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// 加载场景(异步)
        /// </summary>
        /// <param name="info">资源信息标记</param>
        /// <param name="loadingAction">加载中事件</param>
        /// <param name="loadDoneAction">加载完成事件</param>
        /// <returns>加载协程迭代器</returns>
        public IEnumerator LoadSceneAsync(SceneInfo info, HTFAction <float> loadingAction, HTFAction loadDoneAction)
        {
            DateTime beginTime = DateTime.Now;

            if (_isLoading)
            {
                yield return(_loadWait);
            }

            _isLoading = true;

            yield return(LoadDependenciesAssetBundleAsync(info.AssetBundleName));

            DateTime waitTime = DateTime.Now;

            if (LoadMode == ResourceLoadMode.Resource)
            {
                throw new HTFrameworkException(HTFrameworkModule.Resource, "加载场景失败:场景加载不允许使用Resource模式!");
            }
            else
            {
#if UNITY_EDITOR
                if (IsEditorMode)
                {
                    throw new HTFrameworkException(HTFrameworkModule.Resource, "加载场景失败:场景加载不允许使用编辑器模式!");
                }
                else
                {
                    yield return(LoadAssetBundleAsync(info.AssetBundleName, loadingAction));

                    yield return(SceneManager.LoadSceneAsync(info.AssetPath, LoadSceneMode.Additive));
                }
#else
                yield return(LoadAssetBundleAsync(info.AssetBundleName, loadingAction));

                yield return(SceneManager.LoadSceneAsync(info.AssetPath, LoadSceneMode.Additive));
#endif
            }

            DateTime endTime = DateTime.Now;

            Log.Info(string.Format("异步加载场景完成[{0}模式]:{1}\r\n等待耗时:{2}秒  加载耗时:{3}秒"
                                   , LoadMode.ToString()
                                   , info.AssetPath
                                   , (waitTime - beginTime).TotalSeconds
                                   , (endTime - waitTime).TotalSeconds));

            loadDoneAction?.Invoke();

            _isLoading = false;
        }
Exemplo n.º 13
0
        private static IEnumerator RecognitionCoroutine(byte[] data, HTFAction <string> handler, HTFAction failHandler)
        {
            string url = string.Format("{0}?cuid={1}&token={2}", RecognitionAPI, SystemInfo.deviceUniqueIdentifier, TOKEN);

            WWWForm form = new WWWForm();

            form.AddBinaryData("audio", data);

            using (UnityWebRequest request = UnityWebRequest.Post(url, form))
            {
                request.SetRequestHeader("Content-Type", "audio/pcm;rate=16000");
                yield return(request.SendWebRequest());

                if (!request.isNetworkError && !request.isHttpError)
                {
                    JsonData jsonData = GlobalTools.StringToJson(request.downloadHandler.text);
                    if ((int)jsonData["err_no"] == 0)
                    {
                        string text = jsonData["result"].Count > 0 ? jsonData["result"][0].ToString() : "<None>";
                        handler?.Invoke(text);
                    }
                    else
                    {
                        Log.Error("语音识别失败:" + jsonData["err_msg"].ToString());

                        failHandler?.Invoke();
                    }
                }
                else
                {
                    Log.Error("语音识别失败:" + request.responseCode + " " + request.error);

                    failHandler?.Invoke();
                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// 生成对象
        /// </summary>
        /// <returns>对象</returns>
        public GameObject Spawn()
        {
            GameObject obj;

            if (_objectQueue.Count > 0)
            {
                obj = _objectQueue.Dequeue();
            }
            else
            {
                obj = Main.CloneGameObject(_spawnTem);
            }

            obj.SetActive(true);

            _onSpawn?.Invoke(obj);

            return(obj);
        }
Exemplo n.º 15
0
        private static IEnumerator SynthesisByTOKENCoroutine(string text, HTFAction <AudioClip> handler, int timeout, Speaker speaker, int volume, int speed, int pitch)
        {
            string url = string.Format("http://tsn.baidu.com/text2audio?tex='{0}'&tok={1}&cuid={2}&ctp={3}&lan={4}&spd={5}&pit={6}&vol={7}&per={8}&aue={9}",
                                       text, TOKEN, SystemInfo.deviceUniqueIdentifier, 1, "zh", speed, pitch, volume, (int)speaker, 6);

            UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.WAV);

            yield return(request.SendWebRequest());

            if (!request.isNetworkError && !request.isHttpError)
            {
                AudioClip audioClip = SpeechUtility.ToAudioClip(request.downloadHandler.data);

                handler?.Invoke(audioClip);
            }
            else
            {
                GlobalTools.LogError("合成语音失败:" + request.responseCode + " " + request.error);
            }
        }
Exemplo n.º 16
0
        private static IEnumerator SynthesisCoroutine(string text, HTFAction <AudioClip> handler, HTFAction failHandler, int timeout, Speaker speaker, int volume, int speed, int pitch)
        {
            string url = string.Format("{0}?tex='{1}'&tok={2}&cuid={3}&ctp={4}&lan={5}&spd={6}&pit={7}&vol={8}&per={9}&aue={10}",
                                       SynthesisAPI, text, TOKEN, SystemInfo.deviceUniqueIdentifier, 1, "zh", speed, pitch, volume, (int)speaker, 6);

            using (UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.WAV))
            {
                yield return(request.SendWebRequest());

                if (!request.isNetworkError && !request.isHttpError)
                {
                    AudioClip audioClip = DownloadHandlerAudioClip.GetContent(request);

                    handler?.Invoke(audioClip);
                }
                else
                {
                    Log.Error("合成语音失败:" + request.responseCode + " " + request.error);

                    failHandler?.Invoke();
                }
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// 将执行委托排到子线程调用(在主线程中)
        /// </summary>
        /// <param name="action">执行委托</param>
        /// <param name="state">委托的参数</param>
        /// <param name="backToMainThread">执行委托完成后,返回到主线程中回调的委托</param>
        /// <returns>是否执行成功</returns>
        public bool QueueOnSubThread(HTFAction <object> action, object state, HTFAction backToMainThread = null)
        {
            WaitCallback callback = (args) =>
            {
                try
                {
                    action?.Invoke(args);
                }
                catch (Exception e)
                {
                    string error = string.Format("子线程执行中出现异常,子线程方法:{0}.{1},异常信息:{2}", action.Target.GetType().FullName, action.Method.Name, e.Message);
                    Log.Error(error);
                }
                finally
                {
                    if (backToMainThread != null)
                    {
                        QueueOnMainThread(backToMainThread);
                    }
                }
            };

            return(ThreadPool.QueueUserWorkItem(callback, state));
        }
Exemplo n.º 18
0
        private IEnumerator LoadCoroutine <T>(ResourceInfoBase info, HTFAction <float> loadingAction, HTFAction <T> loadDoneAction, bool isPrefab = false, Transform parent = null, bool isUI = false) where T : UnityEngine.Object
        {
            if (_isLoading)
            {
                yield return(_loadWait);
            }

            _isLoading = true;

            UnityEngine.Object asset = null;

            if (Mode == ResourceMode.Resource)
            {
                ResourceRequest request = Resources.LoadAsync <T>(info.ResourcePath);
                while (!request.isDone)
                {
                    loadingAction?.Invoke(request.progress);
                    yield return(null);
                }
                asset = request.asset;
                if (!asset)
                {
                    GlobalTools.LogError("加载资源失败:Resources文件夹中不存在 " + typeof(T) + " 资源 " + info.ResourcePath);
                }
                else
                {
                    if (isPrefab)
                    {
                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                    }
                }
            }
            else
            {
#if UNITY_EDITOR
                loadingAction?.Invoke(1);
                yield return(null);

                asset = AssetDatabase.LoadAssetAtPath <T>(info.AssetPath);
                if (!asset)
                {
                    GlobalTools.LogError("加载资源失败:路径中不存在资源 " + info.AssetPath);
                }
                else
                {
                    if (isPrefab)
                    {
                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                    }
                }
#else
                if (_assetBundles.ContainsKey(info.AssetBundleName))
                {
                    loadingAction?.Invoke(1);
                    yield return(null);

                    asset = _assetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                    if (!asset)
                    {
                        GlobalTools.LogError("加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath);
                    }
                    else
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                }
                else
                {
                    UnityWebRequest            request = UnityWebRequest.Get(_assetBundlePath + info.AssetBundleName);
                    DownloadHandlerAssetBundle handler = new DownloadHandlerAssetBundle(request.url, 0);
                    request.downloadHandler = handler;
                    request.SendWebRequest();
                    while (!request.isDone)
                    {
                        loadingAction?.Invoke(request.downloadProgress);
                        yield return(null);
                    }
                    if (!request.isNetworkError && !request.isHttpError)
                    {
                        if (handler.assetBundle)
                        {
                            asset = handler.assetBundle.LoadAsset <T>(info.AssetPath);
                            if (!asset)
                            {
                                GlobalTools.LogError("加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath);
                            }
                            else
                            {
                                if (isPrefab)
                                {
                                    asset = ClonePrefab(asset as GameObject, parent, isUI);
                                }
                            }

                            if (IsCacheAssetBundle)
                            {
                                if (!_assetBundles.ContainsKey(info.AssetBundleName))
                                {
                                    _assetBundles.Add(info.AssetBundleName, handler.assetBundle);
                                }
                            }
                            else
                            {
                                handler.assetBundle.Unload(false);
                            }
                        }
                        else
                        {
                            GlobalTools.LogError("请求:" + request.url + " 未下载到AB包!");
                        }
                    }
                    else
                    {
                        GlobalTools.LogError("请求:" + request.url + " 遇到网络错误:" + request.error);
                    }
                    request.Dispose();
                    handler.Dispose();
                }
#endif
            }

            if (asset)
            {
                DataSetInfo dataSet = info as DataSetInfo;
                if (dataSet != null && dataSet.Data != null)
                {
                    (asset as DataSet).Fill(dataSet.Data);
                }

                loadDoneAction?.Invoke(asset as T);
            }
            asset = null;

            _isLoading = false;
        }
        /// <summary>
        /// 加载资源(异步)
        /// </summary>
        /// <typeparam name="T">资源类型</typeparam>
        /// <param name="info">资源信息标记</param>
        /// <param name="loadingAction">加载中事件</param>
        /// <param name="loadDoneAction">加载完成事件</param>
        /// <param name="isPrefab">是否是加载预制体</param>
        /// <param name="parent">预制体加载完成后的父级</param>
        /// <param name="isUI">是否是加载UI</param>
        /// <returns>加载协程迭代器</returns>
        public IEnumerator LoadAssetAsync <T>(ResourceInfoBase info, HTFAction <float> loadingAction, HTFAction <T> loadDoneAction, bool isPrefab, Transform parent, bool isUI) where T : UnityEngine.Object
        {
            float beginTime = Time.realtimeSinceStartup;

            //单线加载,如果其他地方在加载资源,则等待
            if (_isLoading)
            {
                yield return(_loadWait);
            }

            //轮到本线路加载资源
            _isLoading = true;

            //等待相关依赖资源的加载
            yield return(LoadDependenciesAssetBundleAsync(info.AssetBundleName));

            float waitTime = Time.realtimeSinceStartup;

            UnityEngine.Object asset = null;

            if (LoadMode == ResourceLoadMode.Resource)
            {
                ResourceRequest request = Resources.LoadAsync <T>(info.ResourcePath);
                while (!request.isDone)
                {
                    loadingAction?.Invoke(request.progress);
                    yield return(null);
                }
                asset = request.asset;
                if (asset)
                {
                    if (isPrefab)
                    {
                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                    }
                }
                else
                {
                    throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:Resources文件夹中不存在资源 " + info.ResourcePath + "!");
                }
            }
            else
            {
#if UNITY_EDITOR
                if (IsEditorMode)
                {
                    loadingAction?.Invoke(1);
                    yield return(null);

                    asset = AssetDatabase.LoadAssetAtPath <T>(info.AssetPath);
                    if (asset)
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                    else
                    {
                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:路径中不存在资源 " + info.AssetPath + "!");
                    }
                }
                else
                {
                    yield return(LoadAssetBundleAsync(info.AssetBundleName, loadingAction));

                    if (AssetBundles.ContainsKey(info.AssetBundleName))
                    {
                        asset = AssetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                        if (asset)
                        {
                            if (isPrefab)
                            {
                                asset = ClonePrefab(asset as GameObject, parent, isUI);
                            }
                        }
                        else
                        {
                            throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                        }
                    }
                }
#else
                yield return(LoadAssetBundleAsync(info.AssetBundleName, loadingAction));

                if (AssetBundles.ContainsKey(info.AssetBundleName))
                {
                    asset = AssetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                    if (asset)
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                    else
                    {
                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                    }
                }
#endif
            }

            float endTime = Time.realtimeSinceStartup;

            //Log.Info(string.Format("异步加载资源{0}[{1}模式]:\r\n{2}\r\n等待耗时:{3}秒  加载耗时:{4}秒"
            //    , asset ? "成功" : "失败"
            //    , LoadMode.ToString()
            //    , LoadMode == ResourceLoadMode.Resource ? info.GetResourceFullPath() : info.GetAssetBundleFullPath(AssetBundleRootPath)
            //    , waitTime - beginTime
            //    , endTime - waitTime));

            if (asset)
            {
                DataSetInfo dataSet = info as DataSetInfo;
                if (dataSet != null && dataSet.Data != null)
                {
                    asset.Cast <DataSetBase>().Fill(dataSet.Data);
                }

                loadDoneAction?.Invoke(asset as T);
            }
            else
            {
                loadDoneAction?.Invoke(null);
            }
            asset = null;

            //本线路加载资源结束
            _isLoading = false;
        }
 public void OnLoading(float progress)
 {
     LoadingHandler?.Invoke(progress);
 }
Exemplo n.º 21
0
        /// <summary>
        /// 加载资源(异步)
        /// </summary>
        /// <typeparam name="T">资源类型</typeparam>
        /// <param name="info">资源信息标记</param>
        /// <param name="loadingAction">加载中事件</param>
        /// <param name="loadDoneAction">加载完成事件</param>
        /// <param name="isPrefab">是否是加载预制体</param>
        /// <param name="parent">预制体加载完成后的父级</param>
        /// <param name="isUI">是否是加载UI</param>
        /// <returns>加载协程迭代器</returns>
        public IEnumerator LoadAssetAsync <T>(ResourceInfoBase info, HTFAction <float> loadingAction, HTFAction <T> loadDoneAction, bool isPrefab, Transform parent, bool isUI) where T : UnityEngine.Object
        {
            DateTime beginTime = DateTime.Now;

            if (_isLoading)
            {
                yield return(_loadWait);
            }

            _isLoading = true;

            yield return(Main.Current.StartCoroutine(LoadDependenciesAssetBundleAsync(info.AssetBundleName)));

            DateTime waitTime = DateTime.Now;

            UnityEngine.Object asset = null;

            if (LoadMode == ResourceLoadMode.Resource)
            {
                ResourceRequest request = Resources.LoadAsync <T>(info.ResourcePath);
                while (!request.isDone)
                {
                    loadingAction?.Invoke(request.progress);
                    yield return(null);
                }
                asset = request.asset;
                if (asset)
                {
                    if (isPrefab)
                    {
                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                    }
                }
                else
                {
                    throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:Resources文件夹中不存在资源 " + info.ResourcePath + "!");
                }
            }
            else
            {
#if UNITY_EDITOR
                if (IsEditorMode)
                {
                    loadingAction?.Invoke(1);
                    yield return(null);

                    asset = AssetDatabase.LoadAssetAtPath <T>(info.AssetPath);
                    if (asset)
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                    else
                    {
                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:路径中不存在资源 " + info.AssetPath + "!");
                    }
                }
                else
                {
                    if (AssetBundles.ContainsKey(info.AssetBundleName))
                    {
                        loadingAction?.Invoke(1);
                        yield return(null);

                        asset = AssetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                        if (asset)
                        {
                            if (isPrefab)
                            {
                                asset = ClonePrefab(asset as GameObject, parent, isUI);
                            }
                        }
                        else
                        {
                            throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                        }
                    }
                    else
                    {
                        using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleRootPath + info.AssetBundleName, GetAssetBundleHash(info.AssetBundleName)))
                        {
                            request.SendWebRequest();
                            while (!request.isDone)
                            {
                                loadingAction?.Invoke(request.downloadProgress);
                                yield return(null);
                            }
                            if (!request.isNetworkError && !request.isHttpError)
                            {
                                AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
                                if (bundle)
                                {
                                    asset = bundle.LoadAsset <T>(info.AssetPath);
                                    if (asset)
                                    {
                                        if (isPrefab)
                                        {
                                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                                        }
                                    }
                                    else
                                    {
                                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                                    }

                                    if (IsCacheAssetBundle)
                                    {
                                        if (!AssetBundles.ContainsKey(info.AssetBundleName))
                                        {
                                            AssetBundles.Add(info.AssetBundleName, bundle);
                                        }
                                    }
                                    else
                                    {
                                        bundle.Unload(false);
                                    }
                                }
                                else
                                {
                                    throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!");
                                }
                            }
                            else
                            {
                                throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!");
                            }
                        }
                    }
                }
#else
                if (AssetBundles.ContainsKey(info.AssetBundleName))
                {
                    loadingAction?.Invoke(1);
                    yield return(null);

                    asset = AssetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                    if (asset)
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                    else
                    {
                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                    }
                }
                else
                {
                    using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleRootPath + info.AssetBundleName, GetAssetBundleHash(info.AssetBundleName)))
                    {
                        request.SendWebRequest();
                        while (!request.isDone)
                        {
                            loadingAction?.Invoke(request.downloadProgress);
                            yield return(null);
                        }
                        if (!request.isNetworkError && !request.isHttpError)
                        {
                            AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
                            if (bundle)
                            {
                                asset = bundle.LoadAsset <T>(info.AssetPath);
                                if (asset)
                                {
                                    if (isPrefab)
                                    {
                                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                                    }
                                }
                                else
                                {
                                    throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                                }

                                if (IsCacheAssetBundle)
                                {
                                    if (!AssetBundles.ContainsKey(info.AssetBundleName))
                                    {
                                        AssetBundles.Add(info.AssetBundleName, bundle);
                                    }
                                }
                                else
                                {
                                    bundle.Unload(false);
                                }
                            }
                            else
                            {
                                throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!");
                            }
                        }
                        else
                        {
                            throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!");
                        }
                    }
                }
#endif
            }

            DateTime endTime = DateTime.Now;

            Log.Info(string.Format("异步加载资源{0}[{1}模式]:\r\n{2}\r\n等待耗时:{3}秒  加载耗时:{4}秒"
                                   , asset ? "成功" : "失败"
                                   , LoadMode.ToString()
                                   , LoadMode == ResourceLoadMode.Resource ? info.GetResourceFullPath() : info.GetAssetBundleFullPath(AssetBundleRootPath)
                                   , (waitTime - beginTime).TotalSeconds
                                   , (endTime - waitTime).TotalSeconds));

            if (asset)
            {
                DataSetInfo dataSet = info as DataSetInfo;
                if (dataSet != null && dataSet.Data != null)
                {
                    asset.Cast <DataSetBase>().Fill(dataSet.Data);
                }

                loadDoneAction?.Invoke(asset as T);
            }
            asset = null;

            _isLoading = false;
        }
 public void OnFinished(bool result)
 {
     FinishedHandler?.Invoke(result);
 }