示例#1
0
    static public void GenFileList()
    {
        DirectoryInfo dir = new DirectoryInfo(AssetBundleLoader.streamingRootPath);

        FileInfo[] files  = dir.GetFiles("*.unity3d", SearchOption.AllDirectories);
        ResInf     resInf = new ResInf();
        var        ver    = VersionMgr.LoadAssetVersion();

#if UNITY_EDITOR
        resInf.version = GitTools.getVerInfo();
#else
        resInf.version = ver.version;
#endif
        resInf.timeCreated = ver.timeCreated;
        resInf.whoCreated  = ver.whoCreated;

        int startIdx = dir.FullName.Length;
        for (int i = 0; i < files.Length; ++i)
        {
            var    file = files[i];
            string md5  = CMD5.MD5File(file.FullName);
            long   siz  = file.Length;
            string path = file.FullName.Substring(startIdx).Replace("\\", "/").Substring(1);
            resInf.Assets.Add(path, new AssetInf(siz, md5));
        }

        string savedPath = EditorStreamingAssetsPath + "/" + FILE_LIST;
        File.WriteAllText(savedPath, TinyJSON.JSON.Dump(resInf, true));

        Log("Generate {0} success.\n => {1}", FILE_LIST, savedPath);
    }
示例#2
0
    /// <summary>
    /// 初始化
    /// </summary>
    public IEnumerator Init()
    {
        // 开始不停的回收资源
        Coroutine.DispatchService(RecycleDaemon());

        // 载入版本控制文件
        yield return(Coroutine.DispatchService(VersionMgr.LoadVersionFile()));

        // 尝试解压资源, 如果是第一次启动游戏则需要将附在包体中的资源
        yield return(Coroutine.DispatchService(ResourceMgr.Instance.DoDecompressRes()));

        // 抛出开始下载资源事件
        //LoadingMgr.ChangeState(ResourceLoadingConst.LOAD_TYPE_UPDATE, ResourceLoadingStateConst.LOAD_STATE_CHECK);

        // 初始化版本控制
        yield return(Coroutine.DispatchService(VersionMgr.CompareOnlineVersion()));

        // 如果下载的大小大于20M,并且在非wifi情况下,给提示
        if (VersionMgr.DownloadSize >= 20 * 1024 * 1024 &&
            Application.internetReachability != NetworkReachability.ReachableViaLocalAreaNetwork)
        {
            bool isConfirmed = false;

            // 可选择更新或者是不更新,不更新直接关闭客户端
            //DialogMgr.ShowSimpleDailog(new CallBack((para, obj) =>
            //{
            //    if ((bool)obj[0])
            //        isConfirmed = true;
            //    else
            //        // 关闭客户端
            //        Application.Quit();
            //}),
            //    string.Format(LocalizationMgr.Get("ResourceLoadingWnd_7", LocalizationConst.START), VersionMgr.DownloadSize/(1024*1024)),
            //    LocalizationMgr.Get("ResourceLoadingWnd_6", LocalizationConst.START),
            //    LocalizationMgr.Get("ResourceLoadingWnd_8", LocalizationConst.START));

            while (!isConfirmed)
            {
                yield return(null);
            }
        }

        // 下载所有需要更新的资源
        yield return(Coroutine.DispatchService(UpdateAllResources()));

        // 等待资源更新完成
        while (!isUpdateResOk)
        {
            yield return(null);
        }

        // 执行更新结束处理
        yield return(Coroutine.DispatchService(VersionMgr.DoSycnResEnd(true)));

        // 载入AssetBundle依赖关系
        yield return(Coroutine.DispatchService(LoadAssetBundleManifest()));

        yield return(null);
    }
示例#3
0
    private void BuildApp()
    {
        const string fileName = "TSK";

#if UNITY_STANDALONE_WIN
        const string FolderName = "PC";
        const string packName   = fileName + ".exe";
#elif UNITY_STANDALONE_OSX
        const string FolderName = "MAC";
        const string packName   = fileName + ".app";
#elif UNITY_ANDROID
        const string FolderName = "AND";
        const string packName   = fileName + ".apk";
#elif UNITY_IOS
        const string FolderName = "IOS";
        const string packName   = fileName + ".ipa";
#endif

#if RY_DEBUG
        const BuildOptions bo = BuildOptions.AllowDebugging | BuildOptions.ConnectWithProfiler;
#else
        const BuildOptions bo = BuildOptions.None;
#endif
        //var verInfo = VersionMgr.LoadAppVersion();
        VersionMgr.SaveAppVersion(GitTools.getVerInfo());
        AssetDatabase.Refresh();

        //清空PC执行文件目录的缓存文件。
        string ProductPath   = Application.dataPath + "/../../Products";
        string ProductPCPath = Path.Combine(ProductPath, FolderName);
        string BuildName     = ProductPCPath + "/" + packName;

        if (!Directory.Exists(ProductPath))
        {
            Directory.CreateDirectory(ProductPath);
        }
        if (!Directory.Exists(ProductPCPath))
        {
            Directory.CreateDirectory(ProductPCPath);
        }

        //开始打游戏包
        BuildPipeline.BuildPlayer(new string[] {
            "Assets/Scenes/ZERO.unity",
        }, BuildName, AssetPacker.buildTarget, bo);

#if UNITY_STANDALONE
        AssetPacker.Log("Coping Essets ...");
        SystemTools.CopyDirectory(Application.dataPath + "/../Essets", ProductPCPath + "/Essets");
#endif

#if UNITY_IOS
        XCodePostProcess.OnPostProcessBuild(BuildName);
#endif

        AssetPacker.Log("Build Done: " + BuildName);
    }
    private void StartVersionCtrl()
    {
        inst_downloadPanel = PanelMgr.CreatePanelFromResources("UI/Prefab/DownloadPanel");
        inst_downloadPanel.AddComponent <DownloadPanelScript>();

        m_versionMgrGo      = new GameObject();
        m_versionMgrGo.name = "VersionMgr";
        VersionMgr m_versionMgr = m_versionMgrGo.AddComponent <VersionMgr>();

        m_versionMgr.InitStart(VersionMgrFinished);
    }
示例#5
0
    static public void PackAssets()
    {
        AssetDatabase.RemoveUnusedAssetBundleNames();
        Artwork.UIChecker.ClearIconReference();

        AssetDatabase.Refresh();

        BuildPipeline.BuildAssetBundles(EditorStreamingAssetsPath, options, buildTarget);

        // 更新资源版本号
        VersionMgr.SaveAssetVersion(GitTools.getVerInfo());
        AssetDatabase.Refresh();

        Log("BuildAssetBundles success.\n => {0}", EditorStreamingAssetsPath);
    }
示例#6
0
    public override void Execute(IMessage message)
    {
        object data = message.Body;

        if (data == null)
        {
            return;
        }

        m_versionMgrGo      = new GameObject();
        m_versionMgrGo.name = "VersionMgr";
        VersionMgr m_versionMgr = m_versionMgrGo.AddComponent <VersionMgr>();

        m_versionMgr.InitStart(VersionMgrFinished);
    }
示例#7
0
    /// <summary>
    /// 尝试解压资源, 如果是第一次启动游戏则需要将附在包体中的资源
    /// 所有随包资源配置在patch_res中
    /// 具体配置格式patch_res={1.7z|2.7z...}
    /// </summary>
    /// <returns>The daemon.</returns>
    public IEnumerator DoDecompressRes()
    {
        //// 抛出开始解压包体中资源事件
        //LoadingMgr.ChangeState(ResourceLoadingConst.LOAD_TYPE_START_DECOMPRESS, ResourceLoadingStateConst.LOAD_STATE_CHECK);

        //// 获取需要解压缩资源列表
        //// 如果没有随包资源,不处理
        //string[] patchRes = ConfigMgr.Get<string[]>("patch_res", new string[]{});
        //if (patchRes.Length == 0)
        //    yield break;

        //// 对比随包版本文件和本地资源版本文件对比判断需要解压具体那些资源
        //yield return Coroutine.DispatchService(VersionMgr.ComparePackageVersion(patchRes));

        //// 如果不需要解压缩不处理
        //if (VersionMgr.UpdateResDict.Count == 0)
        //    yield break;

        //// 抛出开始解压包体中资源事件
        //LoadingMgr.ChangeState(ResourceLoadingConst.LOAD_TYPE_START_DECOMPRESS, ResourceLoadingStateConst.LOAD_STATE_UPDATE);

        //int unzipSize = 0;
        //string targetPath = ConfigMgr.ASSETBUNDLES_PATH + "/";

        //// 获取版本需要更新列表
        //foreach(string file in VersionMgr.UpdateResDict.Keys)
        //{
        //    // 构建解压缩
        //    Unzip zip = new Unzip(ConfigMgr.GetStreamingPathWWW(file), targetPath, VersionMgr.UpdateResDict[file]);

        //    // 开始解压缩
        //    zip.Start();

        //    // 等待解压缩结束
        //    while (! zip.IsUnziped)
        //    {
        //        // 更新进度
        //        LoadingMgr.SetProgress((float) (unzipSize + zip.UnzipBytes) / VersionMgr.UnzipSize);
        //        yield return null;
        //    }

        //    // 释放zip
        //    zip.Clear();

        //    // 主动回收一下资源
        //    DoRecycleGC();

        //    // 如果解压缩失败
        //    /// 0  : 解压缩成功
        //    /// -1 : 压缩文件载入失败
        //    /// -2 : 内存分配失败
        //    /// -3 : 文件写入失败
        //    /// -4 : 其他异常信息
        //    if (zip.Error != 0)
        //    {
        //        string msg = string.Empty;
        //        if (zip.Error == -1)
        //            msg = string.Format(LocalizationMgr.Get("ResourceCheckWnd_21", LocalizationConst.START), file);
        //        else if (zip.Error == -2)
        //            msg = LocalizationMgr.Get("ResourceCheckWnd_22", LocalizationConst.START);
        //        else if (zip.Error == -3)
        //            msg = LocalizationMgr.Get("ResourceCheckWnd_8", LocalizationConst.START);
        //        else
        //        {
        //            // 解压缩失败
        //            msg = string.Format(LocalizationMgr.Get("ResourceCheckWnd_23", LocalizationConst.START), file);
        //        }

        //        // 弹出窗口玩家让玩家确认一下,玩家确认后等待一下会在重试
        //        bool isConfirmed = false;
        //        DialogMgr.ShowSimpleSingleBtnDailog(new CallBack((para, obj) =>
        //                {
        //                    isConfirmed = true;
        //                }), msg);

        //        // 等到玩家确认
        //        while (!isConfirmed)
        //            yield return null;

        //        // 退出游戏
        //        Application.Quit();
        //        yield break;
        //    }
        //    else
        //    {
        //        // 记录解压缩进度
        //        unzipSize += zip.UnzipBytes;

        //        // 更新本地版本文件
        //        VersionMgr.SyncVersion(VersionMgr.UpdateResDict[file]);

        //        // 更新进度
        //        LoadingMgr.SetProgress((float)unzipSize / VersionMgr.UnzipSize);
        //    }
        //}

        //// 更新进度解压缩进度
        //LoadingMgr.SetProgress(1f);

        //// 等待进度条结束
        //while(!LoadingMgr.IsLoadingEnd(LoadingType.LOAD_TYPE_UPDATE_RES,
        //          ResourceLoadingConst.LOAD_TYPE_START_DECOMPRESS))
        //    yield return null;

        // 写入版本文件
        yield return(Coroutine.DispatchService(VersionMgr.DoSycnResEnd(false)));

        yield break;
    }
示例#8
0
    /// <summary>
    /// 更新资源
    /// </summary>
    /// <returns>The daemon.</returns>
    private IEnumerator UpdateAllResources()
    {
        // 重置下载字节数标识
        DownloadedBytes = 0;

        // 获取资源下载地址
        IList abUrls = (IList)ConfigMgr.Get <JsonData> ("ab_urls", null);

        // 没有资源更新地址
        if (abUrls == null || abUrls.Count == 0 || VersionMgr.UpdateResDict.Count == 0)
        {
            // 标识资源更新完成
            isUpdateResOk = true;

            yield break;
        }

        // 抛出开始下载资源事件
        //LoadingMgr.ChangeState(ResourceLoadingConst.LOAD_TYPE_UPDATE, ResourceLoadingStateConst.LOAD_STATE_UPDATE);

        // 获取需要更新资源大小
        int totalDownloadBytes = VersionMgr.DownloadSize;
        int downloadedBytes    = 0;
        int idx = 0;

        // 逐个资源下载
        foreach (string fileName in VersionMgr.UpdateResDict.Keys)
        {
            // 获取资源名
            if (string.IsNullOrEmpty(fileName))
            {
                continue;
            }

            // 保证该资源的download成功
            while (true)
            {
                // 如果idx已经超过了abUrls范围修正一下
                if (idx >= abUrls.Count)
                {
                    idx = 0;
                }

                // 创建下载器
                Download download = new Download(
                    string.Format("{0}/{1}", abUrls[idx], fileName),
                    10,
                    ConfigMgr.DOWNLOAD_PATH + fileName);

                Debug.Log(string.Format("下载补丁包 {0}", download.url));

                // 等待获取头部
                download.StartGetResponse();
                while (!download.isGetResponse && !download.isTimeOut && download.error == 0)
                {
                    yield return(null);
                }

                // GetResponse失败,使用新的链接地址重新下载
                if (!download.isGetResponse || download.error != 0 || download.isTimeOut)
                {
                    // 如果是磁盘空间满的情况,直接退出游戏
                    if (download.error == -2)
                    {
                        // 弹出窗口玩家让玩家确认一下,玩家确认后等待一下会在重试
                        bool isConfirmed = false;
                        //DialogMgr.ShowSimpleSingleBtnDailog(
                        //    new CallBack((para, obj) =>{ isConfirmed = true; }),
                        //    LocalizationMgr.Get("ResourceCheckWnd_8", LocalizationConst.START));

                        // 等到玩家确认
                        while (!isConfirmed)
                        {
                            yield return(null);
                        }

                        // 退出应用
                        Application.Quit();
                        yield break;
                    }

                    idx++;
                    download.Clear();

                    // 等待一会重试
                    yield return(new UnityEngine.WaitForSeconds(0.1f)); // 等待一会重试

                    continue;
                }

                // 开始下载资源
                download.StartDownload();

                // 等待资源下载完成
                while (!download.isDownloaded && !download.isTimeOut && download.error == 0)
                {
                    // 等待0.1s,尽量不要一帧等待
                    yield return(new UnityEngine.WaitForSeconds(0.1f));

                    DownloadedBytes = download.GetTotleDownloadSize() + downloadedBytes;
                    //LoadingMgr.SetProgress (DownloadedBytes/(float)totalDownloadBytes);
                }

                // 如果下载资源失败
                if (download.isTimeOut || download.error != 0)
                {
                    // 如果是磁盘空间满的情况,直接退出游戏
                    if (download.error == -2)
                    {
                        // 弹出窗口玩家让玩家确认一下,玩家确认后等待一下会在重试
                        bool isConfirmed = false;
                        //DialogMgr.ShowSimpleSingleBtnDailog(
                        //    new CallBack((para, obj) =>{ isConfirmed = true; }),
                        //    LocalizationMgr.Get("ResourceCheckWnd_8", LocalizationConst.START));

                        // 等到玩家确认
                        while (!isConfirmed)
                        {
                            yield return(null);
                        }

                        Application.Quit();
                        yield break;
                    }

                    idx++;
                    download.Clear();

                    NIDebug.Log("{0}响应超时或错误", fileName);
                    continue;
                }

                // 累计下载进度
                downloadedBytes += download.GetTotleDownloadSize();

                NIDebug.Log("downloadedBytes 大小{0},oldLoadedBytes 大小为{1}", download.downloadedBytes, download.oldLoadedBytes);
                NIDebug.Log("已下载总量{0}", downloadedBytes);

                // 释放下载器
                download.Clear();

                // 退出循环
                break;
            }
        }

        // 设定更新总进度
        //LoadingMgr.SetProgress (1.0f);

        //// 等待进度条结束
        //while(!LoadingMgr.IsLoadingEnd(LoadingType.LOAD_TYPE_UPDATE_RES,
        //    ResourceLoadingConst.LOAD_TYPE_UPDATE))
        //    yield return null;

        //LoadingMgr.ChangeState(ResourceLoadingConst.LOAD_TYPE_DECOMPRESS, ResourceLoadingStateConst.LOAD_STATE_CHECK);

        //// 切换流程
        //LoadingMgr.ChangeState(ResourceLoadingConst.LOAD_TYPE_DECOMPRESS, ResourceLoadingStateConst.LOAD_STATE_UPDATE);

        // 当前解压缩文件进度
        int    unzipSize     = 0;
        bool   isUnzipFailed = false;
        string targetPath    = ConfigMgr.ASSETBUNDLES_PATH + "/";

        // 资源解压缩
        foreach (string fileName in VersionMgr.UpdateResDict.Keys)
        {
            // 文件名为空
            if (string.IsNullOrEmpty(fileName))
            {
                continue;
            }

            // 构建解压缩
            Unzip zip = new Unzip(
                ConfigMgr.GetLocalRootPathWWW(ConfigMgr.DOWNLOAD_NAME + "/" + fileName),
                targetPath,
                VersionMgr.UpdateResDict[fileName]);

            // 开始解压缩
            zip.Start();

            // 等待解压缩结束
            while (!zip.IsUnziped)
            {
                // 更新进度
                //LoadingMgr.SetProgress((float)(unzipSize + zip.UnzipBytes) / VersionMgr.UnzipSize);
                yield return(null);
            }

            // 累计解压缩数量
            unzipSize += zip.UnzipBytes;
            //LoadingMgr.SetProgress((float)unzipSize / VersionMgr.UnzipSize);

            // 释放zip
            zip.Clear();

            // 回收内存
            DoRecycleGC();

            // 解压缩文件成功
            if (zip.Error == 0)
            {
                // 解压缩成功, 删除补丁文件
                // FileMgr.DeleteFile(ConfigMgr.DOWNLOAD_PATH + "/" + fileName);

                // 更新本地版本文件
                VersionMgr.SyncVersion(VersionMgr.UpdateResDict[fileName]);

                continue;
            }

            // 如果解压缩失败
            /// 0  : 解压缩成功
            /// -1 : 压缩文件载入失败
            /// -2 : 内存分配失败
            /// -3 : 文件写入失败
            /// -4 : 其他异常信息
            string msg = string.Empty;
            //if (zip.Error == -2)
            //    msg = LocalizationMgr.Get("ResourceCheckWnd_22", LocalizationConst.START);
            //else if (zip.Error == -3)
            //    msg = LocalizationMgr.Get("ResourceCheckWnd_8", LocalizationConst.START);

            // 给出提示信息
            if (!string.IsNullOrEmpty(msg))
            {
                // 弹出窗口玩家让玩家确认一下,玩家确认后等待一下会在重试
                bool isConfirmed = false;
                //DialogMgr.ShowSimpleSingleBtnDailog(new CallBack((para, obj) =>
                //        {
                //            isConfirmed = true;
                //        }), msg);

                // 等到玩家确认
                while (!isConfirmed)
                {
                    yield return(null);
                }

                // 退出游戏
                Application.Quit();
                yield break;
            }

            // 标识有资源解压缩失败
            isUnzipFailed = true;

            // 解压缩成功, 删除补丁文件
            //FileMgr.DeleteFile(ConfigMgr.DOWNLOAD_NAME + "/" + fileName);

            // 给出提示信息
            Debug.Log(string.Format("补丁包{0}结果解压缩{1}", fileName, zip.Error));
        }

        // 如果有资源解压缩失败,需要玩家确认重启游戏重新下载资源
        //if (isUnzipFailed)
        //{
        //    // 弹出窗口玩家让玩家确认一下,玩家确认后等待一下会在重试
        //    bool isConfirmed = false;
        //    DialogMgr.ShowSimpleSingleBtnDailog(new CallBack((para, obj) =>
        //        {
        //            isConfirmed = true;
        //        }), LocalizationMgr.Get("ResourceCheckWnd_9", LocalizationConst.START));

        //    // 等到玩家确认
        //    while (! isConfirmed)
        //        yield return null;

        //    // 退出游戏
        //    Application.Quit();
        //    yield break;
        //}


        //// 等待进度条结束
        //while(!LoadingMgr.IsLoadingEnd(LoadingType.LOAD_TYPE_UPDATE_RES,
        //    ResourceLoadingConst.LOAD_TYPE_DECOMPRESS))
        yield return(null);

        // 标识资源更新完成
        isUpdateResOk = true;
    }
示例#9
0
    /// <summary>
    /// 载入资源
    /// </summary>
    private Resource LoadResource(string resPath, bool isDontUnload, bool isSprite = false, bool isAtlas = false)
    {
        Resource res;

        // 尝试获取已加载过的资源, 如果资源还没有加载过则直接加载
        if (!ResourceMap.TryGetValue(resPath, out res))
        {
            // 新建资源
            res = new Resource(resPath, isDontUnload);

            ResourceMap.Add(res.Path, res);
        }

        // 如果资源已经被成功载入了,直接返回资源
        if (res.State == Resource.STATE.LOADED)
        {
            res.LoadSuccessed();
            return(res);
        }

        // 判断是否是ab资源,如果不在版本树上则表示需要本地加载
        string bundle = VersionMgr.GetAssetBundleName(resPath);

        // 尝试载入资源
        try
        {
            // 如果是内部资源
            if (string.IsNullOrEmpty(bundle))
            {
                // 尝试载入资源,如果是编辑器模式则通过UnityEditor.AssetDatabase.LoadAssetAtPath载入
                // 否则通过Resources.Load载入
                if (Platform.IsEditor)
                {
                    // 编辑器测试阶段,直接加载即可
                    // 不是Sprite资源默认UnityEngine.Object
                    if (isSprite)
                    {
                        res.MainAsset = UnityEditor.AssetDatabase.LoadAssetAtPath <UnityEngine.Sprite>(resPath);
                    }
                    else if (isAtlas)
                    {
                        res.MainAsset = UnityEditor.AssetDatabase.LoadAssetAtPath <UIAtlas>(resPath);
                    }
                    else
                    {
                        res.MainAsset = UnityEditor.AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(resPath);
                    }
                }
                else
                {
                    // 默认资源路径Assets/Prefabs/Model/m1011_d.prefab
                    // 最终的目标路径为Prefabs/Model/m1011_d.prefab
                    resPath = resPath.Replace(Path.GetExtension(resPath), string.Empty).Replace("Assets/", string.Empty);

                    // 编辑器测试阶段,直接加载即可
                    // 不是Sprite资源默认UnityEngine.Object
                    if (isSprite)
                    {
                        res.MainAsset = Resources.Load <UnityEngine.Sprite>(resPath);
                    }
                    else if (isAtlas)
                    {
                        res.MainAsset = Resources.Load <UIAtlas>(resPath);
                    }
                    else
                    {
                        res.MainAsset = Resources.Load(resPath);
                    }
                }
            }
            else
            {
                // 获取该bundle依赖资源
                AssetBundle ab;
                string[]    dependentBundles = GetDependentBundle(bundle);
                foreach (string name in dependentBundles)
                {
                    // 载入依赖ab资源
                    ab = LoadAssetBundle(name);

                    // 载入资源成功
                    if (ab == null)
                    {
                        continue;
                    }

                    // 添加资源管理列表
                    if (AB2ResourceMap.ContainsKey(name))
                    {
                        AB2ResourceMap[name].Add(res);
                    }
                    else
                    {
                        AB2ResourceMap[name] = new List <Resource>()
                        {
                            res
                        }
                    };

                    // 添加到资源依赖列表中
                    res.AssetBundles.Add(name);
                }

                // 载入AssetBundle资源
                ab = LoadAssetBundle(bundle);

                // 载入载入成功
                if (ab != null)
                {
                    // 添加资源管理列表
                    if (AB2ResourceMap.ContainsKey(bundle))
                    {
                        AB2ResourceMap[bundle].Add(res);
                    }
                    else
                    {
                        AB2ResourceMap[bundle] = new List <Resource>()
                        {
                            res
                        }
                    };

                    // 通过AssetBundle载入资源
                    if (isSprite)
                    {
                        res.MainAsset = ab.LoadAsset <UnityEngine.Sprite>(resPath);
                    }
                    else if (isAtlas)
                    {
                        res.MainAsset = ab.LoadAsset <UIAtlas>(resPath);
                    }
                    else
                    {
                        res.MainAsset = ab.LoadAsset(resPath);
                    }

                    // 添加到资源依赖列表中
                    res.AssetBundles.Add(bundle);
                }
            }
        }
        catch (Exception e)
        {
            // 给出异常提示信息
            NIDebug.LogException(e);
        }

        // 执行资源载入结果
        if (res.MainAsset != null)
        {
            res.LoadSuccessed();
        }
        else
        {
            res.LoadFaild();
        }

        // 返回资源
        return(res);
    }
示例#10
0
    /// <summary>
    /// 异步加载资源
    /// </summary>
    public IEnumerator LoadAsync(string resPath, bool isDontUnload = false, bool isSprite = false)
    {
        Resource res;

        // 尝试获取已加载过的资源, 如果资源还没有加载过则直接加载
        if (!ResourceMap.TryGetValue(resPath, out res))
        {
            // 新建资源
            res = new Resource(resPath, isDontUnload);
            ResourceMap.Add(res.Path, res);
        }

        // 如果资源已经被成功载入了,直接返回资源
        if (res.State == Resource.STATE.LOADED)
        {
            // 资源载入成功
            res.LoadSuccessed();
            yield break;
        }

        // 判断是否是ab资源,如果不在版本树上则表示需要本地加载
        string bundle = VersionMgr.GetAssetBundleName(resPath);

        // 如果是内部资源
        if (string.IsNullOrEmpty(bundle))
        {
            // 尝试载入资源,如果是编辑器模式则通过UnityEditor.AssetDatabase.LoadAssetAtPath载入
            // 否则通过Resources.Load载入
            if (Platform.IsEditor)
            {
                // 编辑器测试阶段,直接加载即可
                // 不是Sprite资源默认UnityEngine.Object
                if (!isSprite)
                {
                    res.MainAsset = UnityEditor.AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(resPath);
                }
                else
                {
                    res.MainAsset = UnityEditor.AssetDatabase.LoadAssetAtPath <UnityEngine.Sprite>(resPath);
                }
            }
            else
            {
                // 资源异步加载
                ResourceRequest request = null;

                // 默认资源路径Assets/Prefabs/Model/m1011_d.prefab
                // 最终的目标路径为Prefabs/Model/m1011_d
                resPath = resPath.Replace(Path.GetExtension(resPath), string.Empty).Replace("Assets/", string.Empty);

                // 编辑器测试阶段,直接加载即可
                // 不是Sprite资源默认UnityEngine.Object
                if (!isSprite)
                {
                    request = Resources.LoadAsync(resPath);
                }
                else
                {
                    request = Resources.LoadAsync <UnityEngine.Sprite>(resPath);
                }

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

                // 获取asset资源对象
                res.MainAsset = request.asset;
            }
        }
        else
        {
            // 获取该bundle依赖资源
            AssetBundle ab;
            string[]    dependentBundles = GetDependentBundle(bundle);
            foreach (string name in dependentBundles)
            {
                // 载入依赖ab资源
                ab = LoadAssetBundle(name);

                // 载入资源成功
                if (ab == null)
                {
                    continue;
                }

                // 添加资源管理列表
                if (AB2ResourceMap.ContainsKey(name))
                {
                    AB2ResourceMap[name].Add(res);
                }
                else
                {
                    AB2ResourceMap[name] = new List <Resource>()
                    {
                        res
                    }
                };

                // 添加到资源依赖列表中
                res.AssetBundles.Add(name);
            }

            // 载入AssetBundle资源
            ab = LoadAssetBundle(bundle);

            // 载入载入成功
            if (ab != null)
            {
                // 添加资源管理列表
                if (AB2ResourceMap.ContainsKey(bundle))
                {
                    AB2ResourceMap[bundle].Add(res);
                }
                else
                {
                    AB2ResourceMap[bundle] = new List <Resource>()
                    {
                        res
                    }
                };

                // 添加到资源依赖列表中
                if (!res.AssetBundles.Contains(bundle))
                {
                    res.AssetBundles.Add(bundle);
                }

                // 异步载入资源
                AssetBundleRequest assetLoadRequest = null;
                if (!isSprite)
                {
                    assetLoadRequest = ab.LoadAssetAsync(resPath);
                }
                else
                {
                    assetLoadRequest = ab.LoadAssetAsync <UnityEngine.Sprite>(resPath);
                }

                // 等待资源载入完成
                yield return(assetLoadRequest);

                // 记录主要资源
                res.MainAsset = assetLoadRequest.asset;
            }
        }

        // 执行资源载入结果
        if (res.MainAsset != null)
        {
            res.LoadSuccessed();
        }
        else
        {
            res.LoadFaild();
        }
    }

    #endregion
}
示例#11
0
 static int GetVersion(ILuaState lua)
 {
     lua.PushVariant(VersionMgr.LoadAppVersion().ToVariant());
     lua.PushVariant(VersionMgr.LoadAssetVersion().ToVariant());
     return(2);
 }