Exemplo n.º 1
0
    private static IEnumerator LoadSceneByCoroutine(string bundlePath, string sceneName, Action <int> onLoadFinishCallBack)
    {
        //todo 这里应该继续加载所有依赖项
        string[] dependencies = manifest.GetAllDependencies(bundlePath);

        string assetURL = PathDefine.GetAssetUrl(bundlePath);
        var    req      = AssetBundle.LoadFromFileAsync(assetURL);

        yield return(req);

        if (req == null)
        {
            Debug.LogError("加载场景Bundle失败  " + assetURL);
        }
        else
        {
            AssetBundle ab = req.assetBundle;
        }

        AsyncOperation ao = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single);

        yield return(ao);

        if (ao.isDone && onLoadFinishCallBack != null)
        {
            onLoadFinishCallBack.Invoke((int)LocalCode.SUCCESS);
        }

        req.assetBundle.Unload(false);
    }
        static void Main()
        {
            //全局异常捕捉
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            MsgHelper.Instance.Intialize();

            Process[] tProcess = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
            if (tProcess.Length > 1)
            {
                frm_MessageBox.ShowMessage("已有一个进程在运行!!!");
                Application.Exit();
            }
            else
            {
                Application.ApplicationExit += Application_ApplicationExit;

                // 创建系统所需文件夹
                PathDefine.CreatePath();
                MsgHelper.Instance.WriteLog(MsgLevel.Debug, "软件启动");
                Application.Run(new frm_Main());
            }
        }
Exemplo n.º 3
0
    public void DownLoadAssetBundleByList(List <VersionAndSize> list, string pfStr, Action <int> cb)
    {
        for (int i = 0; i < list.Count; i++)
        {
            string path = PathDefine.serverPath(pfStr, (int)list[i].version) + list[i].name;

            int index = i;
            Action <UnityWebRequest> DownloadCB = (request) =>
            {
                if (request.isHttpError || request.isNetworkError)
                {
                    Debug.LogError(request.error + "  -----  " + path);
                    cb((int)LocalCode.DOWNLOAD_BUNDLE_FAULT);
                }
                else
                {
                    downloadIndex++;
                    uiLoadingView.Refresh(downloadIndex, list.Count, "正在下载对应AB文件至本地");

                    if (cb != null && downloadIndex == list.Count)
                    {
                        cb((int)LocalCode.SUCCESS);
                    }
                }
            };

            UnityWebRequestManager.Instance.DownloadFile(path, PathDefine.presitantABPath() + "AssetsBundle/" + list[i].name, DownloadCB);
        }
    }
Exemplo n.º 4
0
    /// <summary>
    /// 通过www加载资源并返回www
    /// </summary>
    /// <param name="resName"></param>
    /// <param name="callback"></param>
    public void LoadResReturnWWW(string path, Action <WWW> callback)
    {
        string url = "";

#if UNITY_EDITOR || UNITY_ANDROID || UNITY_IPHONE
        url = PathDefine.WWW_Local_File_Path(path);
#else
        url = path;
#endif
        //CoroutineMgr.Instance.StartLoadResCoroutine(url, callback);
    }
Exemplo n.º 5
0
    IEnumerator load()
    {
        string abPath = PathDefine.StreamingAssetsPathByPF(Helper.GetPlatformString()) + "AssetsBundle/scene/game.unity3d";
        AssetBundleCreateRequest abcr = AssetBundle.LoadFromFileAsync(abPath, 0);

        yield return(abcr.assetBundle);

        AssetBundle ab = abcr.assetBundle;

        AsyncOperation ao = SceneManager.LoadSceneAsync("Game", LoadSceneMode.Single);

        ab.Unload(false);
    }
Exemplo n.º 6
0
    public static void BuildAssetBundleEditor()
    {
        AssetBundle.UnloadAllAssetBundles(true);
        SetBundleNameAll();
        string dir = Helper.CheckPathExistence(PathDefine.StreamingAssetsPathByPF("Editor") + "AssetsBundle/");

        if (Directory.Exists(dir) == false)
        {
            Directory.CreateDirectory(dir);
        }
        BuildAssetBundleOptions options  = BuildAssetBundleOptions.DeterministicAssetBundle;
        AssetBundleManifest     manifest = BuildPipeline.BuildAssetBundles(dir, options, BuildTarget.StandaloneWindows64);

        string[] allAssetBundlesName = manifest.GetAllAssetBundles();

        JsonData allJsonData = new JsonData()
        {
        };

        allJsonData["VersionCode"] = GameSetting.Instance.versionCode;
        allJsonData["ABHashList"]  = new JsonData();
        for (int i = 0; i < allAssetBundlesName.Length; i++)
        {
            Hash128 hash     = manifest.GetAssetBundleHash(allAssetBundlesName[i]);
            int     hashCode = hash.GetHashCode();

            JsonData curABData = new JsonData();
            curABData[allAssetBundlesName[i]] = hashCode;

            allJsonData["ABHashList"].Add(curABData);
        }

        //总AssetBundle数据 手动加上
        JsonData assetBundleABData = new JsonData();

        assetBundleABData["AssetsBundle"] = manifest.GetHashCode();
        allJsonData["ABHashList"].Add(assetBundleABData);

        string json = Helper.JsonTree(allJsonData.ToJson());

        byte[] byteArray = System.Text.Encoding.Default.GetBytes(json.ToString());

        //存一份version
        string   jsonSavePathLocal = PathDefine.StreamingAssetsPath("Editor") + "Version/version.json";
        FileInfo fileInfoLocal     = new FileInfo(jsonSavePathLocal);

        Helper.SaveAssetToLocalFile(Helper.CheckPathExistence(fileInfoLocal.Directory.FullName), fileInfoLocal.Name, byteArray);

        AssetDatabase.Refresh();
    }
Exemplo n.º 7
0
    private static void CheckInit()
    {
        if (manifest != null)
        {
            return;
        }

        string      mainBundleUrl = PathDefine.GetAssetUrl("AssetsBundle");
        AssetBundle mainBundle    = AssetBundle.LoadFromFile(mainBundleUrl, 0);

        if (mainBundle == null)
        {
            Debug.LogError("找不到AssetsBundle  " + mainBundleUrl);
            Debug.LogError(LocalCode.DOWNLOAD_ASSETBUNDLEFILE_FAULT);
        }

        manifest = mainBundle.LoadAsset("AssetBundleManifest") as AssetBundleManifest;
        mainBundle.Unload(false);
    }
Exemplo n.º 8
0
    private void LoadLocalVersionJsonObject(Action <VersionJsonObject> onLoadVersionCallBack)
    {
        string versionPath = PathDefine.StreamingAssetsPathByPF(Helper.GetPlatformString()) + "Version/version.json";

        Action <UnityWebRequest> DownloadCB = (request) =>
        {
            if (request.isNetworkError || request.isHttpError)
            {
                Debug.Log(request.error);
            }
            else
            {
                if (onLoadVersionCallBack != null)
                {
                    onLoadVersionCallBack.Invoke(Helper.LoadVersionJson(request.downloadHandler.text));
                }
            }
        };

        UnityWebRequestManager.Instance.DownloadBuffer(versionPath, DownloadCB);
    }
Exemplo n.º 9
0
 /// <summary>
 /// 构建URL
 /// </summary>
 /// <param name="resName"></param>
 /// <param name="resType"></param>
 /// <returns></returns>
 public static string BuildUrl(string resName, ResType resType)
 {
     return(PathDefine.WWW_Path(BuildPath(resName, resType)));
 }
Exemplo n.º 10
0
    /// <summary>
    /// 上传AB 上传的时候需要生成AB版本文件
    /// </summary>
    private void Upload()
    {
        //区分平台
        string pfStr = string.Empty;

        if (platform == 0)
        {
            pfStr = "Editor";
        }
        else if (platform == 1)
        {
            pfStr = "Android";
        }
        else if (platform == 2)
        {
            pfStr = "Ios";
        }

        Debug.Log("正在上传" + pfStr + "平台的AssetsBundle");

        #region 处理AllPackageVersion.json文件
        JsonData allPackageVersionData = new JsonData()
        {
        };
        string allPackageVersionDataPath = PathDefine.serverPathInLocal_AllPackageVersion(pfStr);
        string pristinePkgVersionText    = string.Empty;

        //新版本信息
        JsonData curPackageVersionData = new JsonData();
        curPackageVersionData["Version"]      = version;
        curPackageVersionData["isNewPackage"] = isNewPackage;

        //检查版本文件(记录isnewpackage)路径是否有文件
        if (File.Exists(allPackageVersionDataPath))
        {
            //有就直接加载
            pristinePkgVersionText = File.ReadAllText(allPackageVersionDataPath, System.Text.Encoding.UTF8);

            JsonData jsonData = JsonMapper.ToObject(pristinePkgVersionText);
            for (int i = 0; i < jsonData.Count; i++)
            {
                allPackageVersionData.Add(jsonData[i]);
            }

            //检查当前版本是否已经在文件内
            bool versionIsInFile = false;
            for (int i = 0; i < allPackageVersionData.Count; i++)
            {
                if (int.Parse(allPackageVersionData[i]["Version"].ToString()) == version)
                {
                    allPackageVersionData[i]["isNewPackage"] = isNewPackage;
                    versionIsInFile = true;
                    break;
                }
            }

            if (!versionIsInFile)
            {
                allPackageVersionData.Add(curPackageVersionData);
            }
        }
        else
        {
            allPackageVersionData.Add(curPackageVersionData);
        }

        //将pkgJson数据转化成byte[]
        string pkgJson          = Helper.JsonTree(allPackageVersionData.ToJson());
        byte[] pkgJsonByteArray = System.Text.Encoding.Default.GetBytes(pkgJson.ToString());

        FileInfo pkgFileInfo = new FileInfo(allPackageVersionDataPath);
        Helper.SaveAssetToLocalFile(Helper.CheckPathExistence(pkgFileInfo.Directory.FullName), pkgFileInfo.Name, pkgJsonByteArray);

        #endregion

        #region 移动有变动的AB到指定文件夹
        //先把对应版本文件夹删掉
        if (Directory.Exists(PathDefine.serverPathInLocal(pfStr, version)))
        {
            Helper.DeleteFiles(PathDefine.serverPathInLocal(pfStr, version));
        }

        //获取最后的版本,然后去对应文件夹查找相应的AssetBundle文件
        int serverRecentVersion = 0;
        if (isNewPackage)
        {
            serverRecentVersion = version;
        }
        else
        {
            if (allPackageVersionData.Count == 1)
            {
                //误操作提示
                Debug.LogError("上传热更版本前需要有一个整包版本,当前已退出上传AB流程,请检查版本");
                return;
            }
            serverRecentVersion = int.Parse(allPackageVersionData[allPackageVersionData.Count - 2]["Version"].ToString());
        }

        List <string> shouldMoveList = new List <string>();

        AssetBundle         localAssetBundle = AssetBundle.LoadFromFile(PathDefine.StreamingAssetsPath(pfStr) + "AssetsBundle/AssetsBundle");
        AssetBundleManifest localABManifest  = localAssetBundle.LoadAsset <AssetBundleManifest>("AssetBundleManifest");
        localAssetBundle.Unload(false);

        AssetBundle         serverAssetBundle = null;
        AssetBundleManifest serverABManifest  = null;
        if (!isNewPackage)
        {
            serverAssetBundle = AssetBundle.LoadFromFile(PathDefine.serverPathInLocal(pfStr, serverRecentVersion) + "AssetsBundle");
            serverABManifest  = serverAssetBundle.LoadAsset <AssetBundleManifest>("AssetBundleManifest");
            serverAssetBundle.Unload(false);
        }

        string[] localAllABName = localABManifest.GetAllAssetBundles();

        for (int i = 0; i < localAllABName.Length; i++)
        {
            Hash128 localHash  = localABManifest.GetAssetBundleHash(localAllABName[i]);
            Hash128 serverHash = new Hash128();
            if (serverABManifest != null)
            {
                serverHash = serverABManifest.GetAssetBundleHash(localAllABName[i]);
            }

            if (serverABManifest == null)//说明是新包,全部增加
            {
                shouldMoveList.Add(localAllABName[i]);
            }
            else if (localHash.GetHashCode() != serverHash.GetHashCode())//说明是改动过的
            {
                shouldMoveList.Add(localAllABName[i]);
            }
        }

        //上面的localABManifest.GetAllAssetBundles()没有包含这个文件,补上
        //这个文件每次都会被改动到
        shouldMoveList.Add("AssetsBundle");

        //移动AB包
        for (int i = 0; i < shouldMoveList.Count; i++)
        {
            string targetPath = PathDefine.serverPathInLocal(pfStr, version) + shouldMoveList[i];

            string[] targetPathGroup = targetPath.Split('/');

            string needCheckDirectoryPath = string.Empty;//需要检查的文件夹地址
            for (int j = 0; j < targetPathGroup.Length - 1; j++)
            {
                needCheckDirectoryPath = needCheckDirectoryPath + (j == 0 ? string.Empty : "/") + targetPathGroup[j];
            }
            Helper.CheckPathExistence(needCheckDirectoryPath);

            byte[] fileByte = File.ReadAllBytes(PathDefine.StreamingAssetsPath(pfStr) + "AssetsBundle/" + shouldMoveList[i]);

            FileStream fsDes = File.Create(targetPath);
            fsDes.Write(fileByte, 0, fileByte.Length);
            fsDes.Flush();
            fsDes.Close();
        }
        #endregion

        #region 创建fileversion.json文件
        JsonData newFileInfoJsonData = new JsonData()
        {
        };
        //判断是否全新整包
        if (isNewPackage)
        {
            for (int i = 0; i < shouldMoveList.Count; i++)
            {
                //拼接AB版本文件,用于记录每个AB的版本
                byte[]   b  = File.ReadAllBytes(PathDefine.StreamingAssetsPath(pfStr) + "AssetsBundle/" + shouldMoveList[i]);
                JsonData jd = CreteFileVersionItemJson(shouldMoveList[i], version, b.Length);
                newFileInfoJsonData.Add(jd);
            }
        }
        else
        {
            string recentFileInfoText = File.ReadAllText(PathDefine.serverPathInLocal(pfStr, serverRecentVersion) + "fileversion.json", System.Text.Encoding.UTF8);
            newFileInfoJsonData = JsonMapper.ToObject(recentFileInfoText);

            //检查替换
            for (int i = 0; i < newFileInfoJsonData.Count; i++)
            {
                for (int j = 0; j < shouldMoveList.Count; j++)
                {
                    if (shouldMoveList[j] == newFileInfoJsonData[i]["name"].ToString())
                    {
                        //下面需要补充info
                        byte[] b = File.ReadAllBytes(PathDefine.StreamingAssetsPath(pfStr) + "AssetsBundle/" + shouldMoveList[j]);
                        newFileInfoJsonData[i]["info"][0]["version"] = version;
                        newFileInfoJsonData[i]["info"][0]["size"]    = b.Length;
                        break;
                    }
                }
            }

            //检查新增
            for (int i = 0; i < shouldMoveList.Count; i++)
            {
                bool isAdd = true;
                for (int j = 0; j < newFileInfoJsonData.Count; j++)
                {
                    //检查新增的文件名是否在fileversion文件内
                    if (shouldMoveList[i] == newFileInfoJsonData[j]["name"].ToString())
                    {
                        isAdd = false;
                        break;
                    }
                }

                if (isAdd)
                {
                    byte[]   b  = File.ReadAllBytes(PathDefine.StreamingAssetsPath(pfStr) + "AssetsBundle/" + shouldMoveList[i]);
                    JsonData jd = CreteFileVersionItemJson(shouldMoveList[i], version, b.Length);
                    newFileInfoJsonData.Add(jd);
                }
            }
        }

        string verJson   = Helper.JsonTree(newFileInfoJsonData.ToJson());
        byte[] byteArray = System.Text.Encoding.Default.GetBytes(verJson.ToString());

        //保存版本文件
        string saveFileVersionPath = PathDefine.serverPathInLocal(pfStr, version) + "fileversion.json";
        if (File.Exists(saveFileVersionPath))
        {
            File.Delete(saveFileVersionPath);
            AssetDatabase.Refresh();
        }
        FileInfo verFileInfo = new FileInfo(saveFileVersionPath);
        Helper.SaveAssetToLocalFile(Helper.CheckPathExistence(verFileInfo.Directory.FullName), verFileInfo.Name, byteArray);

        #endregion

        #region 创建version.json文件 用于对比HASH 下载
        JsonData versionJsonData = new JsonData()
        {
        };

        versionJsonData["VersionCode"] = version;
        versionJsonData["ABHashList"]  = new JsonData();
        for (int i = 0; i < localAllABName.Length; i++)
        {
            Hash128  localHash = localABManifest.GetAssetBundleHash(localAllABName[i]);
            JsonData curABData = new JsonData();
            curABData[localAllABName[i]] = localHash.GetHashCode();

            versionJsonData["ABHashList"].Add(curABData);
        }

        //添加当前总AB文件的HASH对比
        JsonData assetsBundleJD = new JsonData();
        assetsBundleJD["AssetsBundle"] = localABManifest.GetHashCode();
        versionJsonData["ABHashList"].Add(assetsBundleJD);

        string json = Helper.JsonTree(versionJsonData.ToJson());
        byte[] versionJsonByteArray = System.Text.Encoding.Default.GetBytes(json.ToString());

        //存一份version
        string   jsonSavePathLocal = PathDefine.serverPathInLocal(pfStr, version) + "version.json";
        FileInfo fileInfoLocal     = new FileInfo(jsonSavePathLocal);
        Helper.SaveAssetToLocalFile(Helper.CheckPathExistence(fileInfoLocal.Directory.FullName), fileInfoLocal.Name, versionJsonByteArray);
        #endregion
        Debug.Log("上传完毕");
    }
Exemplo n.º 11
0
    /// <summary>
    /// 检查热更
    /// </summary>
    /// <param name="finalCB"></param>
    public void Check(Action <int> finalCB)
    {
        //平台名称
        string pfStr = Helper.GetPlatformString();

        //后台版本号
        int serverVersionCode = -1;

        VersionIsNewPackage server_vinp = null;//服务器版本对应的包体信息

        List <VersionIsNewPackage> allPackageVersionList = new List <VersionIsNewPackage>();

        System.Action <System.Action <int> >[] tasks = new System.Action <System.Action <int> > [4];

        tasks[0] = (cb) =>
        {
            //先用UnityWebRequest加载本地version.json文件
            string path        = string.Empty;
            bool   isExitsInPD = File.Exists(PathDefine.presitantABPath() + "Version/version.json");
            Debug.Log("isExitsInPD  " + isExitsInPD);
            if (isExitsInPD)
            {
                path = PathDefine.presitantABPath() + "Version/version.json";
            }
            else
            {
                path = PathDefine.StreamingAssetsPathByPF(pfStr) + "Version/version.json";
            }

            uiLoadingView.Refresh(0, 1, "读取本地版本信息文件中");

            Action <UnityWebRequest> DownloadCB = (request) =>
            {
                if (request.isNetworkError || request.isHttpError)
                {
                    Debug.Log(request.error);
                    cb((int)LocalCode.DOWNLOAD_VERSIONJSON_FAULT);
                }
                else
                {
                    localVersionJsonObj = Helper.LoadVersionJson(request.downloadHandler.text);
                    cb((int)LocalCode.SUCCESS);
                }
            };

            UnityWebRequestManager.Instance.DownloadBuffer(path, DownloadCB);
        };

        tasks[1] = (cb) =>
        {
            //获取当前可升级到的版本(模拟访问PHP返回数据) 现在并不需要对数据做任何处理
            WWWForm wwwForm = new WWWForm();
            wwwForm.headers.Add("headersKey", "headersValue");
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes("getVersion");
            wwwForm.AddBinaryData(byteArray.ToString(), byteArray);
            Debug.Log("请求服务器下发可运行版本");
            UnityWebRequestManager.Instance.Post("http://192.168.1.175/GetVersion:8080/", wwwForm, (request) =>
            {
                if (request.isNetworkError || request.isHttpError)
                {
                    Debug.Log(request.error);
                    cb((int)LocalCode.REQ_SERVER_VERSION_CODE_FAULT);
                }
                else
                {
                    Debug.Log(" unitywebrequest 收到服务器下发可运行版本 版本号为:" + request.downloadHandler.text);
                    serverVersionCode = int.Parse(request.downloadHandler.text);
                    cb((int)LocalCode.SUCCESS);
                }
            });
        };

        tasks[2] = (cb) =>
        {
            //拿到服务器版本之后 先判断当前版本是否需要热更(先判断presitantDataPath里面有没有这个文件,若没有 则使用GameSetting里面的VersionCode)
            //若需要热更新 去CDN(即本地服务器的AssetsBundle目录)下载AllPackageVersion.json

            Action <UnityWebRequest> DownloadCB = (request) =>
            {
                if (request.isNetworkError || request.isHttpError)
                {
                    Debug.Log(request.error);
                    cb((int)LocalCode.DOWNLOAD_ALL_PACKAGEVERSION_FAULT);
                }
                else
                {
                    JsonData jsonData = JsonMapper.ToObject(request.downloadHandler.text);
                    int      count    = jsonData.Count;

                    for (int i = 0; i < count; i++)
                    {
                        JsonData verIsNewPkgJD = jsonData[i];

                        VersionIsNewPackage vinp = new VersionIsNewPackage();
                        vinp.version      = uint.Parse(verIsNewPkgJD["Version"].ToJson());
                        vinp.isNewPackage = bool.Parse(verIsNewPkgJD["isNewPackage"].ToJson());

                        allPackageVersionList.Add(vinp);
                    }

                    // 下载完了AllPackageVersion.json
                    // 根据服务器下发的版本去资源库取对应版本资源
                    // 资源库里面有一个文件记录当前版本是否热更版本的文件
                    // 然后判断当前资源库版本是否是热更版本

                    server_vinp = allPackageVersionList.Find(t => t.version == serverVersionCode);

                    if (server_vinp != null)
                    {
                        if (true == server_vinp.isNewPackage)
                        {
                            //不需要更新

                            //GameSetting.Instance.versionCode 这个值是在出包的时候设置的
                            //判断在PC上出整包的版本是否是服务器上的最新版本
                            if (GameSetting.Instance.versionCode == serverVersionCode)
                            {
                                cb((int)LocalCode.PATCHER_END);
                            }
                            else
                            {
                                //需要换包
                                cb((int)LocalCode.CUR_SERVERVER_IS_NEWPACKAGE);
                            }
                        }
                        else
                        {
                            //需要更新
                            cb((int)LocalCode.SUCCESS);
                        }
                    }
                    else
                    {
                        //在资源库中找不到对应版本资源
                        cb((int)LocalCode.CAN_NOT_FIND_VERSION_IN_CDN);
                    }
                }
            };

            //用于判断当前版本是整包版本还是热更版本
            if (serverVersionCode > localVersionJsonObj.version)//判断服务器版本是否大于当前版本
            {
                UnityWebRequestManager.Instance.DownloadBuffer(PathDefine.serverPath(pfStr) + "AllPackageVersion.json", DownloadCB);
            }
            else
            {
                //当前版本已是最新 无需更新
                cb((int)LocalCode.CUR_VER_IS_NEWEST);
            }
        };

        tasks[3] = (cb) =>
        {
            //到达此步  已经下载完AllPackageVersion.json
            //本地的version.json文件在上面已经加载好了
            //需要再去服务器上拿最新的version.json文件
            //对比哪些文件需要下载

            Action <UnityWebRequest> DownloadCB = (request) =>
            {
                if (request.isHttpError || request.isNetworkError)
                {
                    Debug.LogError(request.error + "  -----  下载服务端上的Version.json失败");
                    cb((int)LocalCode.DOWNLOAD_VERSIONJSON_FAULT);
                }
                else
                {
                    VersionJsonObject serverVersionJson = Helper.LoadVersionJson(request.downloadHandler.text);

                    if (serverVersionJson.version > localVersionJsonObj.version) //服务器版本大于本地版本
                    {
                        //下面检测该下哪些Bundle
                        foreach (ABNameHash singleServiceNameHash in serverVersionJson.ABHashList)
                        {
                            VersionJsonObject aa = localVersionJsonObj;
                            ABNameHash        singleLocalNameHash = localVersionJsonObj.ABHashList.Find(t => t.abName == singleServiceNameHash.abName);
                            if (singleLocalNameHash != null)
                            {
                                if (singleLocalNameHash.hashCode != singleServiceNameHash.hashCode)
                                {
                                    shouldDownloadList.Add(singleServiceNameHash.abName);
                                }
                            }
                            else
                            {
                                shouldDownloadList.Add(singleServiceNameHash.abName);
                            }
                        }

                        //保存当前这份最新的 version.json 文件
                        byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(request.downloadHandler.text);
                        Helper.SaveAssetToLocalFile(PathDefine.presitantABPath(), "Version/version.json",
                                                    byteArray);
                        localVersionJsonObj = serverVersionJson;
                        GameSetting.Instance.versionCode = (int)serverVersionJson.version;
                    }

                    if (shouldDownloadList.Count > 0)
                    {
                        //拿到对应的fileversion  然后取版本号
                        //取到版本号之后开始从资源库上对应文件夹下载资源
                        string fileVersionPath = PathDefine.serverPath(pfStr, serverVersionCode) + "fileversion.json";

                        Action <UnityWebRequest> DownloadFileVersionCB = (fileVersionRequest) =>
                        {
                            if (fileVersionRequest.isNetworkError || fileVersionRequest.isHttpError)
                            {
                                Debug.LogError(fileVersionRequest.error);
                                cb((int)LocalCode.DOWNLOAD_FILEVERSIONJSON_FAULT);
                            }
                            else
                            {
                                FileVersionJsonObject fileVersionJsonObject = Helper.LoadFileVersionJson(fileVersionRequest.downloadHandler.text);
                                //保存当前这份最新的 fileversion.json 文件
                                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(fileVersionRequest.downloadHandler.text);
                                Helper.SaveAssetToLocalFile(PathDefine.presitantABPath(), "FileVersion/fileversion.json", byteArray);

                                List <VersionAndSize> vasList = new List <VersionAndSize>();
                                foreach (string name in shouldDownloadList)
                                {
                                    Debug.LogError("download AB -----  " + name);
                                    VersionAndSize vas = fileVersionJsonObject.versionSizeList.Find(t => t.name == name);
                                    vasList.Add(vas);
                                }

                                AssetBundleManager.Instance.DownLoadAssetBundleByList(vasList, pfStr, cb);
                            }
                        };

                        UnityWebRequestManager.Instance.DownloadBuffer(fileVersionPath, DownloadFileVersionCB);
                    }
                    else
                    {
                        Debug.LogError("没有可更新的");
                    }
                }
            };

            UnityWebRequestManager.Instance.DownloadBuffer(PathDefine.serverPath(pfStr, serverVersionCode) + "version.json", DownloadCB);
        };

        AsyncHelper asyncHelper = new AsyncHelper();

        asyncHelper.Waterfall(tasks, finalCB);
    }
Exemplo n.º 12
0
    public override bool Load(Priority priority, out bool process)
    {
        allSpriteAtlasDict = new Dictionary <string, SpriteAtlas>();
        int dCount   = 0;
        int allCount = 0;

        Action <Dictionary <string, SpriteAtlas> > dataLoadCallBack = (dict) =>
        {
            dCount++;
            foreach (KeyValuePair <string, SpriteAtlas> item in dict)
            {
                allSpriteAtlasDict.Add(item.Key, item.Value);
            }
            if (onLoadSingleFinishCallBack != null)
            {
                onLoadSingleFinishCallBack.Invoke(dCount, allCount);
            }
            if (dCount == allCount)
            {
                if (onLoadAllFinishCallBack != null)
                {
                    onLoadAllFinishCallBack.Invoke(allSpriteAtlasDict);
                }
            }
        };

        switch (GameSetting.Instance.runType)
        {
        case RunType.PATCHER_SA_PS:
            FileVersionJsonObject fileVersion = AssetBundleManager.Instance.fileVersionJsonObject;
            List <VersionAndSize> vasList     = fileVersion.versionSizeList.FindAll(t => t.name.Contains("spriteatlas/"));
            allCount = vasList.Count;
            for (int i = 0; i < vasList.Count; i++)
            {
                string saPath = PathDefine.StreamingAssetsPathByPF(Helper.GetPlatformString()) + "AssetsBundle/" + vasList[i].name;;
                string pdPath = PathDefine.presitantABPath() + vasList[i].name;
                string path   = vasList[i].version <= GameSetting.Instance.versionCode ? saPath : pdPath;

                AssetBundleLoader.LoadSpriteAtlas(path, dataLoadCallBack);
            }
            break;

        case RunType.NOPATCHER_SA:
            Action <VersionJsonObject> loadVersionJsonCallBack = (versionJson) =>
            {
                List <string>     abNameList     = new List <string>();
                List <ABNameHash> abNameHashList = versionJson.ABHashList;
                for (int i = 0; i < abNameHashList.Count; i++)
                {
                    if (abNameHashList[i].abName.Contains("spriteatlas/"))
                    {
                        abNameList.Add(abNameHashList[i].abName);
                    }
                }
                allCount = abNameList.Count;
                for (int i = 0; i < abNameList.Count; i++)
                {
                    string path = PathDefine.StreamingAssetsPathByPF(Helper.GetPlatformString()) + "AssetsBundle/" + abNameList[i];
                    AssetBundleLoader.LoadSpriteAtlas(path, dataLoadCallBack);
                }

                if (abNameList.Count == 0)
                {
                    onLoadAllFinishCallBack.Invoke(allSpriteAtlasDict);
                }
            };

            LoadLocalVersionJsonObject(loadVersionJsonCallBack);
            break;

        case RunType.NOPATCHER_RES:
            string[]      spriteAtlasPath    = Helper.GetFiles("Assets/SpriteAtlas/SpriteAtlas/", null, true, true);
            List <string> shouldLoadFileList = new List <string>();
            for (int i = 0; i < spriteAtlasPath.Length; i++)
            {
                if (!spriteAtlasPath[i].Contains(".meta"))
                {
                    shouldLoadFileList.Add(spriteAtlasPath[i]);
                }
            }

            allCount = shouldLoadFileList.Count;
            for (int i = 0; i < shouldLoadFileList.Count; i++)
            {
                ResourcesLoader.LoadSpriteAtlas(shouldLoadFileList[i], dataLoadCallBack);
            }
            break;
        }

        process = true;
        return(true);
    }
Exemplo n.º 13
0
    private static IEnumerator LoadAssetByCoroutine(string bundlePath, string name, Action <UnityEngine.Object> onLoadFinishCallBack)
    {
        string assetURL = PathDefine.GetAssetUrl(bundlePath);

        AssetBundle ab = null;

        AssetBundleCreateRequest req = null;

        if (abDict.ContainsKey(bundlePath))
        {
            ab = abDict[bundlePath];
        }
        else
        {
            Debug.LogError("assetURL  " + assetURL);
            req = AssetBundle.LoadFromFileAsync(assetURL);
            ab  = req.assetBundle;
            abDict.Add(bundlePath, ab);
        }

        yield return(ab);

        if (ab == null)
        {
            Debug.LogError("加载  " + bundlePath + "  失败----");
            onLoadFinishCallBack.Invoke(null);
        }
        else
        {
            UnityEngine.GameObject o = null;
            if (gameObjectPool.ContainsKey(name))
            {
                o = gameObjectPool[name];
            }
            else
            {
                o = ab.LoadAsset <GameObject>(name);
                gameObjectPool.Add(name, o);
            }

            //这里应该继续加载所有依赖项
            string[]           dependencies = manifest.GetAllDependencies(bundlePath);
            List <AssetBundle> abList       = new List <AssetBundle>();
            if (dependencies.Length > 0)
            {
                for (int i = 0; i < dependencies.Length; i++)
                {
                    int index = i;

                    string depPath = PathDefine.GetAssetUrl(dependencies[i]);
                    var    de      = AssetBundle.LoadFromFileAsync(depPath);
                    yield return(de);

                    abList.Add(de.assetBundle);
                }
                onLoadFinishCallBack.Invoke(o);

                for (int i = 0; i < abList.Count; i++)
                {
                    abList[i].Unload(false);
                }
            }
            else
            {
                onLoadFinishCallBack.Invoke(o);
            }
        }
    }