protected bool ExtractAndWriteDownFile(string compressDir, string destDir, string fileName, byte[] data) { //write to file bool bRet = AssetBundleUtil.WriteToFile(compressDir, fileName, data); if (!bRet) { m_error = String.Format("WriteToFile: {0} failed", compressDir + fileName); return(false); } //解压缩文件 string compressFilePath = compressDir + fileName; int ret = DodLibUtil.GetDodLib().Decompress7zip(compressFilePath, destDir); if (ret != 1) { BLogger.Error("doDecompress7zip failed: {0}, Ret:{1}", compressFilePath, ret); m_error = StartupTextConfigMgr.Instance.GetText(StartupTextDefine.ID_STARTUP_UPDATE_EXTRACT_DOWNFILE_FAILED, fileName, ret); return(false); } //删除压缩文件 AssetBundleUtil.DeleteFile(compressFilePath); return(true); }
protected override void _Start() { base.Open(); AssetBundleUtil.Load(); buttonCreate.onClick.AddListener(delegate { UGUITree.current.CloseStart(); Floor.current.Reset(); MyCamera.current.Reset(); PanelList.current.Reset(); }); buttonLoad.onClick.AddListener(delegate { PanelLoad.current.Open(); }); #if UNITY_EDITOR platform = "hi,大家好,我是在unity编辑模式下"; #elif UNITY_XBOX360 platform = "hi,大家好,我在XBOX360平台"; #elif UNITY_IPHONE platform = "hi,大家好,我是IPHONE平台"; #elif UNITY_ANDROID platform = "hi,大家好,我是ANDROID平台"; #elif UNITY_STANDALONE_OSX platform = "hi,大家好,我是OSX平台"; #elif UNITY_STANDALONE_WIN platform = "hi,大家好,我是Windows平台"; #endif Debug.Log("Current Platform:" + platform); }
bool LoadCacheAndTimeConfig(string configText) { try { var allConfigList = MiniJSON.Json.Deserialize(configText) as List <object>; if (null == allConfigList) { BLogger.Error("parse depends json error"); return(false); } for (int i = 0; i < allConfigList.Count; i++) { Dictionary <string, object> dictItem = allConfigList[i] as Dictionary <string, object>; string assetPath = AssetBundleUtil.ReadJsonKey <string>(dictItem, "asset"); int cacheTime = (int)AssetBundleUtil.ReadJsonKey <Int64>(dictItem, "time"); int poolCnt = (int)AssetBundleUtil.ReadJsonKey <Int64>(dictItem, "poolcnt"); XResource.RegCacheResPath(assetPath, cacheTime, poolCnt); BLogger.Info("[{0}]cache resource[{1}] cache time: {2} pool max count:{3}", i, assetPath, cacheTime, poolCnt); } return(true); } catch (Exception e) { BLogger.Error("LoadCacheAndTimeConfig failed: " + e.ToString()); return(false); } }
void InitAbStartup() { AssetBundleConfig.InitConfig(true); AssetBundleUtil.SetExternAssetBundleDir(GetAbDir()); #if UNITY_IPHONE XFileUtil.SetFolderNoSaveImp((folderPath) => { UnityEngine.iOS.Device.SetNoBackupFlag(folderPath); }); #endif AssetBundleUtil.m_abHashMd5 = false; GameCoreConfig.UseAssetBundle = true; #if UNITY_EDITOR AssetBundleUtil.traceAssetBundleDebug = false; #endif InitFileProtocol(); BLogger.Info("******dataPath: {0}", Application.dataPath); BLogger.Info("******streamingAssetsPath:{0}", Application.streamingAssetsPath); BLogger.Info("******temporaryCachePath:{0}", Application.temporaryCachePath); BLogger.Info("******persistentDataPath:{0}", Application.persistentDataPath); BLogger.Info("******asset bundle dir: {0}", GetAbDir()); BLogger.Info("******storage free space:{0}", ReleaseUtil.GetStorageFreeSpace()); }
/// <summary> /// 读取资源的缓存策略 /// </summary> void ReadResourceCacheConfig() { string cachePath = "Config/CacheConfig/need_cache_list"; TextAsset needCacheListAsset = XResource.LoadAsset <TextAsset>(cachePath); TextAsset needPersistListAsset = XResource.LoadAsset <TextAsset>("Config/CacheConfig/need_persist_list"); if (needCacheListAsset != null) { string configText = StringUtility.UTF8BytesToString(needCacheListAsset.bytes); if (!LoadCacheAndTimeConfig(configText)) { BLogger.Warning("-------------LoadCacheAndTimeConfig failed: {0}", cachePath); } } else { BLogger.Error("read need cache resource list config failed"); } if (needPersistListAsset != null) { List <string> needPersistList = AssetBundleUtil.ReadTextStringList(needPersistListAsset.bytes); if (needPersistList != null) { XResource.RegPersistResPath(needPersistList); BLogger.Info("-------------register need persist res list: {0}", needPersistList.Count); } } else { BLogger.Error("read need persist resource list config failed"); } }
//-------------------------------------------------------------------------------------------- // 生成普通资源包 static public void BuildGamePack(string file, List <string> fLst, BuildTarget tgt, bool silence, BundleVersionControl version) { file = file.ToLower(); string szNm = GetTargetName(tgt); string msg = @"确定要生成 " + szNm + @" 客户端资源包吗? 这个过程可能会很漫长"; if (silence || EditorUtility.DisplayDialog(@"游戏版本发布", msg, "Ok", "Cancel")) { if (AssetBundleUtil.ExportToBundle(fLst, file, tgt, version)) { msg = szNm + @" 客户端资源包已生成, 存放于: " + file; if (!silence) { EditorUtility.DisplayDialog(@"操作已完成", msg, "Ok"); } else { Debug.Log(msg); } } else { msg = szNm + @" 客户端资源包生成失败,是否继续???"; for (int i = 0; i < fLst.Count; i++) { msg += "\r\n" + fLst[i]; } //EditorUtility.DisplayDialog(@"操作失败", msg, "Ok"); if (!EditorUtility.DisplayDialog(@"操作失败", msg, "Ok", "Cancel")) { throw new System.Exception("error file:" + file); } } } }
private void InitFileProtocol() { #if UNITY_EDITOR AssetBundleUtil.SetFileProtocol("file:///"); #else AssetBundleUtil.SetFileProtocol("file://"); #endif }
private VfsSystem VfsIphoneCreateAbSystem() { VfsSystem abVfs = new VfsSystem(); //优先读取sdcard里的ab目录 abVfs.AddVfsDriver(new VfsLocalFsDriver(AssetBundleUtil.GetExternAssetBundleDir())); //, "file://")); abVfs.AddVfsDriver(new VfsLocalFsDriver(Application.streamingAssetsPath + "/ab/")); //, "file://")); return(abVfs); }
IEnumerator FetchTile(Vector2 index) { string fileName = index[0] + "." + index[1] + ".lnd"; string host = DEBUG ? "http://lvh.me/tiles" : "https://decentraland.org/content"; string url = host + "/" + fileName; Vector3 pos = indexToPosition(index); // Temporal Placeholder GameObject plane = Instantiate(baseTile, pos, Quaternion.identity); GameObject loader = Instantiate(loading, pos, Quaternion.identity); loader.transform.position = new Vector3(pos.x, pos.y + 2, pos.z); WWW www = new WWW(url); yield return(www); if (!string.IsNullOrEmpty(www.error)) { Debug.Log("Can't fetch tile content! " + index + " " + www.error); names.Add(index, "Unclaimed Land"); Destroy(loader); } else { Debug.Log("Downloaded content for tile (" + index[0] + "," + index[1] + ")"); try { // TODO: fix decompression effort; // byte[] blob = CLZF2.Decompress(www.bytes); // // Debug.Log("Data length:"); // Debug.Log(www.bytes.Length); // Debug.Log("Decompressed length:"); // Debug.Log(blob.Length); var bundle = AssetBundleUtil.GetBundleFromBytes(www.bytes); var prefab = AssetBundleUtil.LoadAssetBundle <GameObject>(bundle); var go = Instantiate <GameObject>(prefab); bundle.Unload(false); Destroy(prefab); go.transform.position = pos; names.Add(index, go.name); } catch (EndOfStreamException e) { Debug.Log("Invalid" + index + e.ToString()); } catch (SerializationException e) { Debug.Log("Invalid" + index + e.ToString()); } catch (Exception e) { Debug.Log("Exception found in " + index + e.ToString()); } finally { Destroy(loader); } } }
/// <summary> /// 分配Bundle /// </summary> /// <param name="outputPath">输出路径</param> /// <param name="scenePrefabPath">资源的绝对路径</param> private void assignBundle(string outputPath, string scenePrefabPath) { string sceneName = Path.GetFileNameWithoutExtension(scenePrefabPath); string relativeScenePath = scenePrefabPath.Replace(Application.dataPath, "Assets"); string[] depAssetArr = AssetDatabase.GetDependencies(relativeScenePath); string rootPath = Path.GetDirectoryName(scenePrefabPath).Replace("\\", "/"); rootPath = rootPath.Replace(Application.dataPath, "Assets"); string relativePath = outputPath.Replace(BuildGlobal.EXPORT_BUNDLE_ROOT, ""); string bundleName = relativePath + "/" + sceneName + "_" + curBuildConfig.AssetType; foreach (string defAsset in depAssetArr) { string suffix = Path.GetExtension(defAsset); if (BuildGlobal.FilterAsset.Contains(suffix)) { continue; } if (defAsset.StartsWith(rootPath)) { AssetBundleUtil.AssignBundle(defAsset, bundleName); } else { //记录引用,避免公共集合打包时,把不必要的资源也打要进来 AssetBuildEditor.Instance.AddDependencie(curBuildConfig.BundleName, defAsset); // //如果依赖是资源处于公共资源目录 // //检查资源是否被分配,如果没有则依据目录进行分配 // BuildConfig buildConf = BuildConfigManager.Instance.FindAssetBuildConfig(defAsset); // if (buildConf == null) // { // Debug.LogWarning("<<SceneStrategy , assignBundle>> Cant find build config ! asset path is " + defAsset); // continue; // } // // string dirName = buildConf.InputDir.Substring(buildConf.InputDir.LastIndexOf("/") + 1); // if (string.IsNullOrEmpty(dirName)) // { // if(buildConf.InputDir.IndexOf("/") < 0) // dirName = buildConf.InputDir; // } // AssetBundleUtil.AssignBundle(defAsset , dirName); } } //分配自身的Bundle AssetBundleUtil.AssignBundle(scenePrefabPath, bundleName); }
private bool CheckFileCrc(Crc32 crc, string path, uint expectCrc) { //判断crc是否一致,如果一致,则是已经下载了一半的文件 byte[] downData = AssetBundleUtil.ReadFile(path); if (downData != null) { uint crcVal = crc.ComputeChecksum(downData); return(crcVal == expectCrc); } return(false); }
private VfsSystem VfsWindowsCreateAbSystem() { VfsSystem abVfs = new VfsSystem(); //优先读取sdcard里的ab目录 abVfs.AddVfsDriver(new VfsLocalFsDriver(AssetBundleUtil.GetExternAssetBundleDir()));//, "file:///")); /*abVfs.AddVfsDriver(new VfsLocalFsDriver(Application.dataPath + "/../ab_enc/cab/", * "file:///"));*/ abVfs.AddVfsDriver(new VfsLocalFsDriver(Application.dataPath + "/../ab_enc/ab/"));/*, * "file:///"));*/ return(abVfs); }
private bool LoadRootBaseInfo(string content) { m_localRootMeta = AssetBundleUtil.ParseRootMeta(content); if (string.IsNullOrEmpty(m_localRootMeta.m_version)) { m_error = "read local version failed"; return(false); } BaseConfigInfo.AbVersion = m_localRootMeta.m_version; BaseConfigInfo.IsAssetLua = m_localRootMeta.m_isLua; return(true); }
private static void BuildAssetBundles(BuildTarget buildTarget) { var outputPath = Path.Combine(AssetBundlesOutputPath, AssetBundleUtil.GetPlatformFolderForAssetBundles(buildTarget)); if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } const BuildAssetBundleOptions options = BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.ForceRebuildAssetBundle; BuildPipeline.BuildAssetBundles(outputPath, options, buildTarget); }
public void BeginProcess(BuildConfig buildConfig) { string absolutionPath = Path.Combine(Application.dataPath, buildConfig.InputDir); string[] findFile = buildConfig.FileSuffixs.Split('|'); //查找打包输入路径下的根目录列表 string[] dirArr = Directory.GetDirectories(absolutionPath, "*", SearchOption.TopDirectoryOnly); foreach (string subDir in dirArr) { DirectoryInfo di = new DirectoryInfo(subDir); //将文件夹的名字做为Bundle名称 AssetBundleUtil.MulInOneBundle(di.Name, buildConfig.AssetType, subDir, findFile, buildConfig.OptionSerach); } }
public void ReadConfig() { configDic.Clear(); if (!File.Exists(allPath)) { return; } string configJson = File.ReadAllText(allPath); BuildConfig[] configs = AssetBundleUtil.FromJsonArray <BuildConfig>(ref configJson); foreach (BuildConfig buildConfig in configs) { AddBuildConfig(buildConfig); } }
public void BeginProcess(BuildConfig buildConfig) { string absolutionPath = Path.Combine(Application.dataPath, buildConfig.InputDir); string[] findFile = buildConfig.FileSuffixs.Split('|'); List <string> files = new List <string>(); foreach (string fileSuffix in findFile) { string[] fileArr = Directory.GetFiles(absolutionPath, fileSuffix, buildConfig.OptionSerach); files.AddRange(fileArr); } //为文件分配到指定Bundle List <string> allBundleFile = new List <string>(); string bundleName = buildConfig.BundleName + "_" + buildConfig.AssetType; foreach (string filePath in files) { string relativePath = filePath.Replace("\\", "/"); relativePath = relativePath.Replace(Application.dataPath, "Assets"); List <string> bundleFiles = AssetBuildEditor.Instance.AssignBundle(bundleName, relativePath, buildConfig.BundleName); allBundleFile.AddRange(bundleFiles); } //如果存在PreBuild , 则有可能是公共目录资源,同时检查资源冗余 if (string.IsNullOrEmpty(buildConfig.PreBuild) || buildConfig.PreBuild == "None") { return; } List <string> refAssets = AssetBuildEditor.Instance.GetBundleRefList(buildConfig.BundleName); foreach (string asset in refAssets) { allBundleFile.Remove(asset); } //清理多余的资源 foreach (string asset in allBundleFile) { AssetBundleUtil.ClearBundle(asset); } }
//-------------------------------------------------------------------------------------------- // 把场景文件也加到资源索引表里 static void AppendResPackItm(string[] szAry, string fpck, BuildTarget tgt) { Dictionary <string, ResPackItm> tbl = new Dictionary <string, ResPackItm>(); string szPckNm = Path.GetFileName(fpck); szPckNm = szPckNm.ToLower(); foreach (string sf in szAry) { string szKey = Path.GetFileName(sf).ToLower(); ResPackItm itm = new ResPackItm(); itm.mType = 1; // 场景资源 itm.mfVer = 1; //// 需要查找对应版本号 itm.mFile = szKey; itm.mPack = szPckNm; tbl.Add(szKey, itm); } AssetBundleUtil.WriteResList(tbl, tgt); }
public void SaveConfig() { string jsonStr = AssetBundleUtil.ToJsonArray(BuildConfigs); if (string.IsNullOrEmpty(jsonStr)) { return; } string dir = Path.GetDirectoryName(allPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllText(allPath, jsonStr); }
public byte[] LoadStreamAsset(string path) { var fullPath = Application.streamingAssetsPath + "/" + path; byte[] data = null; if (fullPath.Contains("://")) { #if UNITY_ANDROID && !UNITY_EDITOR data = DodLib.LoadStreamAssetFile(fullPath); #endif } else { data = AssetBundleUtil.ReadFile(fullPath); } return(data); }
void Start() { var windowsBundlePath = AssetBundleUtil.FullPathForAssetBundleName("Windows"); var windowsBundle = AssetBundle.LoadFromFile(windowsBundlePath); var manifest = windowsBundle.LoadAsset <AssetBundleManifest>("AssetBundleManifest"); manifest.GetAllAssetBundles() .ToList() .ForEach(Debug.Log); manifest.GetAllDependencies("coin_get_prefab") .ToList() .ForEach(dependBundle => Debug.LogFormat("coin_get_prefab depends:{0}", dependBundle)); windowsBundle.Unload(true); }
private byte[] LoadStreamAsset(string path) { var fullPath = Application.streamingAssetsPath + "/" + path; byte[] data = null; if (fullPath.Contains("://")) { if (!DPlatform.IsEditorPlatform() && DPlatform.IsAndroidPlatform()) { data = DodLibUtil.GetDodLib().LoadStreamAssetFile(fullPath); } } else { data = AssetBundleUtil.ReadFile(fullPath); } return(data); }
private VfsSystem VfsAndroidCreateAbSystem() { VfsSystem abVfs = new VfsSystem(); //优先读取sdcard里的ab目录 var localPath = AssetBundleUtil.GetExternAssetBundleDir(); abVfs.AddVfsDriver(new VfsLocalFsDriver(localPath));//, "file://")); BLogger.Info("Init local fs driver: {0}", localPath); string zipPath = Application.dataPath; abVfs.AddVfsDriver(new ZipVfsDriver(zipPath)); BLogger.Info("Init driver zipPath: {0}", zipPath); return(abVfs); }
public bool ReadBaseInfo() { m_error = null; //m_allMd5List = new Dictionary<string, AssetMd5FileInfo>(); m_localAssetMd5Dict.Clear(); m_localIndexList.Clear(); m_loadedAllAssetMd5 = false; string path = AssetBundleUtil.GetExternAssetBundleDir() + AssetBundleUtil.MD5HASH_FILE_ROOT_NAME; string content = AssetBundleUtil.ReadTextFile(path); if (content == null) { m_error = "Read file failed: " + path; return(false); } if (!LoadRootBaseInfo(content)) { return(false); } List <AssetMd5FileInfo> list = ParseAssetMd5List(path, content); if (list != null) { m_localIndexList.Capacity = list.Count; foreach (AssetMd5FileInfo indexFileInfo in list) { m_localIndexList.Add(indexFileInfo.m_md5FilePath); if (m_localAssetMd5Dict.ContainsKey(indexFileInfo.m_md5FilePath)) { BLogger.Error("file entry repeated: {0}", indexFileInfo.m_md5FilePath); return(false); } m_localAssetMd5Dict.Add(indexFileInfo.m_md5FilePath, indexFileInfo); } } return(true); }
protected override void LoadNewPage() { List <Item> items = GetItems(); List <GameObject> list = new List <GameObject>(); item.SetActive(true); foreach (Item p in items) { Transform clone = Instantiate(item, content).transform; clone.Find("Name").GetComponentInChildren <Text>().text = p.name; clone.Find("Size").GetComponentInChildren <Text>().text = p.size; Transform operate = clone.Find("Operate"); operate.Find("ButtonLoad").gameObject.SetActive(false); operate.Find("ButtonDelete").GetComponent <Button>().onClick.AddListener(delegate { AssetBundleUtil.Clear(); DirectoryInfo directoryInfo = new DirectoryInfo(MyWebRequest.current.LOCAL_ASSET_PATH); foreach (FileInfo fi in directoryInfo.GetFiles()) { Debug.Log(fi.Name); fi.Delete(); } foreach (DirectoryInfo di in directoryInfo.GetDirectories()) { Debug.Log(di.Name); foreach (FileInfo fi in di.GetFiles()) { Debug.Log(fi.Name); fi.Delete(); } di.Delete(); } // directoryInfo.Delete(); }); list.Add(clone.gameObject); } item.SetActive(false); pageCache.Add(nowIndex, list); pages = 1; FreshNavigation(); }
public void BeginProcess(BuildConfig buildConfig) { curBuildConfig = buildConfig; string absolutionInputPath = Path.Combine(Application.dataPath, buildConfig.InputDir); string[] sceneFilePathArr = System.IO.Directory.GetFiles(absolutionInputPath, "*.unity", SearchOption.AllDirectories); foreach (string scenePath in sceneFilePathArr) { string scenePrefab = scenePath.Replace(".unity", ".prefab"); scenePrefab = scenePrefab.Replace("\\", "/"); if (!File.Exists(scenePrefab)) { continue; } assignBundle(AssetBundleUtil.FormatOutputPath(buildConfig), scenePrefab); } }
public bool LoadLocalAllAssetMd5() { if (m_loadedAllAssetMd5) { BLogger.Warning("local asset md5 has loaded"); return(true); } m_loadedAllAssetMd5 = true; string path = AssetBundleUtil.GetExternAssetBundleDir() + AssetBundleUtil.MD5HASH_FILE_ROOT_NAME; //读取本地所有的文件配置信息 foreach (string indexFile in m_localIndexList) { path = AssetBundleUtil.GetExternAssetBundleDir() + indexFile; string content = AssetBundleUtil.ReadTextFile(path); if (content == null) { m_error = "Read file failed: " + path; return(false); } var list = ParseAssetMd5List(path, content); if (list != null) { foreach (AssetMd5FileInfo indexFileInfo in list) { if (m_localAssetMd5Dict.ContainsKey(indexFileInfo.m_md5FilePath)) { BLogger.Error("file entry repeated: {0}", indexFileInfo.m_md5FilePath); return(false); } m_localAssetMd5Dict.Add(indexFileInfo.m_md5FilePath, indexFileInfo); } } } return(true); }
/// <summary> /// 读取ab缓存的配置 /// </summary> /// <returns></returns> private bool LoadAbCacheConfig() { TextAsset needPersistAsset = XResource.LoadAsset <TextAsset>("Config/AbConfig/need_persist_assetbundle"); if (needPersistAsset == null) { BLogger.Error("read resource failed: {0}", "need_persist_assetbundle"); return(false); } List <string> listAbPath = AssetBundleUtil.ReadTextStringList(needPersistAsset.bytes); List <string> listMd5Path = new List <string>(); foreach (string abPath in listAbPath) { listMd5Path.Add(AssetBundleUtil.GetPathHash(abPath)); } AssetBundlePool.Instance.RegPersistAssetBundlePath(listMd5Path); //Logger.Error("regist persist assetbundle count: {0}", listMd5Path.Count); return(true); }
public IEnumerator CheckRepairIndex() { if (haveErr) { yield break; } Crc32 crc = new Crc32(); string abDir = AssetBundleUtil.GetExternAssetBundleDir(); var enumerator = m_latestAssetMd5Dict.GetEnumerator(); while (enumerator.MoveNext()) { var md5FileInfo = enumerator.Current.Value; var fileName = md5FileInfo.m_md5FilePath; string filePath = abDir + fileName; if (!AssetBundleUtil.IsFileExist(filePath)) { string path = Path.GetFileNameWithoutExtension(fileName); if (!AssetBundleLoader.Instance.IsCanFastCreateAb(path)) { AssetMd5FileInfo info; if (!m_localAssetMd5Dict.TryGetValue(fileName, out info) || info.m_crc != md5FileInfo.m_crc) { TryAddDownFile(md5FileInfo); } } else { TryAddDownFile(md5FileInfo); } } else if (!CheckFileCrc(crc, filePath, md5FileInfo.m_crc)) { TryAddDownFile(md5FileInfo); } } }
/// <summary> /// 分配Bundle /// </summary> /// <param name="bundleName">Bundle名称</param> /// <param name="assetPath">资源的绝对路径</param> /// <param name="buildConfigName">配置的名称</param> public List <string> AssignBundle(string bundleName, string assetPath, string buildConfigName) { string relativeScenePath = assetPath.Replace(Application.dataPath, "Assets"); string[] depAssetArr = AssetDatabase.GetDependencies(relativeScenePath); string rootPath = Path.GetDirectoryName(assetPath).Replace("\\", "/"); rootPath = rootPath.Replace(Application.dataPath, "Assets"); List <string> allBundleFiles = new List <string>(); foreach (string defAsset in depAssetArr) { string suffix = Path.GetExtension(defAsset); if (BuildGlobal.FilterAsset.Contains(suffix)) { continue; } if (defAsset.StartsWith(rootPath)) { AssetBundleUtil.AssignBundle(defAsset, bundleName); allBundleFiles.Add(defAsset); } else { //记录引用,避免公共集合打包时,把不必要的资源也打要进来 AddDependencie(buildConfigName, defAsset); } } //分配自身的Bundle AssetBundleUtil.AssignBundle(assetPath, bundleName); allBundleFiles.Add(assetPath); return(allBundleFiles); }