public static void ClearPersistentDataPath() { foreach (string dir in Directory.GetDirectories(KResourceModule.GetAppDataPath())) { Directory.Delete(dir, true); } foreach (string file in Directory.GetFiles(KResourceModule.GetAppDataPath())) { File.Delete(file); } }
/// <summary> /// 目前用在非热更部分,lua中请使用OpenWindow /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T GetOrCreateUI <T>() where T : UIController, new() { var type = typeof(T); UIController uiBase = null; dict.TryGetValue(type, out uiBase); if (uiBase != null) { return(uiBase as T); } uiBase = new T(); uiBase.IsGameBaseUI = true; dict.Add(type, uiBase); var res_path = KResourceModule.GetAbFullPath($"ui/{uiBase.UITemplateName.ToLower()}"); var assetBundle = AssetBundle.LoadFromFile(res_path); var t = assetBundle.LoadAsset <GameObject>(uiBase.UITemplateName); GameObject uiObj = GameObject.Instantiate(t); //TODO 管理图集 if (uiObj) { var windowAsset = uiObj.GetComponent <UIWindowAsset>(); if (windowAsset && !string.IsNullOrEmpty(windowAsset.atals_arr)) { string[] arr = windowAsset.atals_arr.Split(','); int sprite_count = 0; for (int i = 0; i < arr.Length; i++) { string atlas_name = arr[i].ToLower(); if (!UIModule.Instance.CommonAtlases.Contains(atlas_name)) { sprite_count++; var atlas = assetBundle.LoadAsset <SpriteAtlas>(atlas_name); if (atlas != null) { ABManager.SpriteAtlases[atlas_name] = atlas; } } } if (sprite_count >= 2) { Log.LogError($"UI:{uiBase.UITemplateName}包括多个图集({windowAsset.atals_arr}),请处理"); } } } assetBundle.Unload(false); uiBase.gameObject = uiObj; uiBase.transform = uiObj.transform; uiBase.UIName = uiBase.UITemplateName; uiBase.OnInit(); return(uiBase as T); }
/// <summary> /// whether the script file exists? /// </summary> /// <param name="scriptRelativePath"></param> /// <returns></returns> public bool HasScript(string scriptRelativePath) { var scriptPath = GetScriptPath(scriptRelativePath); if (Log.IsUnityEditor) { return(File.Exists(scriptPath)); } else { return(KResourceModule.IsStreamingAssetsExists(scriptPath)); } }
public void RelaseSpriteLoader() { KAsync.Start().WaitForSeconds(5).Then(() => { foreach (KeyValuePair <string, AssetBundleLoader> keyValuePair in spriteLoaders) { keyValuePair.Value.Release(true); } Destroy(targetImage); KResourceModule.Collect(); }); }
/// <summary> /// After Init Modules, coroutine /// </summary> /// <returns></returns> public override IEnumerator OnGameStart() { WaitForSeconds wait = new WaitForSeconds(1); while (DownloadManager.Instance.DownloadFinish == false) { yield return(wait); } Log.Info(I18N.Get("btn_billboard")); // Print AppConfigs // Log.Info("======================================= Read Settings from C# ================================="); foreach (BillboardSetting setting in BillboardSettings.GetAll()) { Debug.Log(string.Format("C# Read Setting, Key: {0}, Value: {1}", setting.Id, setting.Title)); } //加载公共图集 AssetBundleLoader.Load($"uiatlas/{UIModule.Instance.CommonAtlases[0]}", (isOk, ab) => { if (isOk && ab) { var atlas = ab.LoadAsset <SpriteAtlas>("atlas_common"); ABManager.SpriteAtlases["atlas_common"] = atlas; } }); yield return(null); UIModule.Instance.OpenWindow("UILogin", 888); // Test Load a scene in asset bundle SceneLoader.Load("Scene/Scene1001/Scene1001"); //预加载公告界面 // UIModule.Instance.PreLoadUIWindow("Billboard"); //UIModule.Instance.OpenWindow("Billboard"); // 测试Collect函数,立即回收所有资源 var path = "ui/UIRoleInfo"; var assetLoader = AssetBundleLoader.Load(path); while (!assetLoader.IsCompleted) { yield return(null); } yield return(new WaitForSeconds(1)); assetLoader.Release(); KResourceModule.Collect(); }
private IEnumerator LoadUIAssetBundle(string name, UILoadState openState, KCallback callback = null) { if (openState.UIResourceLoader != null) { openState.UIResourceLoader.Release();// now! KResourceModule.Collect(); Log.Info("Release UI ResourceLoader: {0}", openState.UIResourceLoader.Url); openState.UIResourceLoader = null; } LoadingUICount++; var request = new UILoadRequest(); yield return(KResourceModule.Instance.StartCoroutine(UiBridge.LoadUIAsset(openState, request))); GameObject uiObj = (GameObject)request.Asset; // 具体加载逻辑结束...这段应该放到Bridge里 uiObj.SetActive(false); uiObj.name = openState.TemplateName; var uiBase = UiBridge.CreateUIController(uiObj, openState.TemplateName); if (openState.UIWindow != null) { Log.Info("Destroy exist UI Window, maybe for reload"); GameObject.Destroy(openState.UIWindow.CachedGameObject); openState.UIWindow = null; } openState.UIWindow = uiBase; uiBase.UIName = uiBase.UITemplateName = openState.TemplateName; UiBridge.UIObjectFilter(uiBase, uiObj); openState.IsLoading = false; // Load完 InitWindow(openState, uiBase, openState.OpenWhenFinish, openState.OpenArgs); LoadingUICount--; if (callback != null) { callback(null); } }
/// <summary> /// Default load setting strategry, /// </summary> /// <param name="path"></param> /// <returns></returns> public static byte[] DefaultLoadSetting(string path) { string fullUrl; var getResPathType = KResourceModule.GetResourceFullPath(GetTextFilePath(path), false, out fullUrl); if (getResPathType == KResourceModule.GetResourceFullPathType.Invalid) { Log.Error("can not find file: {0}", fullUrl); return(null); } var bytes = File.ReadAllBytes(fullUrl); bytes = SettingBytesFilter != null?SettingBytesFilter(bytes) : bytes; return(bytes); }
/// <summary> /// Call script of script path (relative) specify /// /// We don't recommend use this method, please use ImportScript which has Caching! /// </summary> /// <param name="scriptRelativePath"></param> /// <returns></returns> public object CallScript(string scriptRelativePath) { if (string.IsNullOrEmpty(scriptRelativePath)) { return(null); } var scriptPath = GetScriptPath(scriptRelativePath); if (!KResourceModule.IsResourceExist(scriptPath)) { return(null); } byte[] script = KResourceModule.LoadAssetsSync(scriptPath); var ret = ExecuteScript(script, scriptRelativePath); return(ret); }
void DrawBuildUI() { GUILayout.BeginHorizontal("HelpBox"); EditorGUILayout.LabelField("== 生成安装包 =="); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("打PC版", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformWinReleaseBuild(); } if (GUILayout.Button("打PC版-Dev", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformWinBuild(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("打Android版", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformAndroidBuild(); } if (GUILayout.Button("打IOS版", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformiOSBuild(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("打开安装包目录", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { var path = AppConfig.ProductRelPath + "/Apps/" + KResourceModule.GetBuildPlatformName(); OpenFolder(path); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.EndHorizontal(); }
/// <summary> /// Call script of script path (relative) specify /// /// We don't recommend use this method, please use ImportScript which has Caching! /// </summary> /// <param name="scriptRelativePath"></param> /// <returns></returns> public object CallScript(string scriptRelativePath) { if (scriptRelativePath == null || string.IsNullOrEmpty(scriptRelativePath)) { return(null); } var scriptPath = GetScriptPath(scriptRelativePath); if (!KResourceModule.IsResourceExist(scriptPath)) { return(null); } byte[] script = KResourceModule.LoadAssetsSync(scriptPath); Debuger.Assert(script != null, $"ExecuteScript error,script byte null,path:{scriptPath}"); var ret = ExecuteScript(script, scriptRelativePath); return(ret); }
private static void OnPostProcessScene() { if (!_hasBeforeBuildApp && !EditorApplication.isPlayingOrWillChangePlaymode) { _hasBeforeBuildApp = true; // 这里是编译前, 对Lua进行编译处理 Debug.Log("[LuaModuleEditor]Start compile lua script..."); var luaPath = AppEngine.GetConfig("KSFramework.Lua", "LuaPath"); var ext = AppEngine.GetConfig("KEngine", "AssetBundleExt"); var luaCount = 0; var editorLuaScriptPath = Path.Combine(KResourceModule.EditorProductFullPath, luaPath); editorLuaScriptPath = editorLuaScriptPath.Replace("\\", "/"); if (!Directory.Exists(editorLuaScriptPath)) { return; } var toDir = "Assets/StreamingAssets/" + KResourceModule.BundlesDirName + "/" + KResourceModule.GetBuildPlatformName() + "/" + luaPath; // 所有的Lua脚本拷贝到StreamingAssets foreach (var path in Directory.GetFiles(editorLuaScriptPath, "*", SearchOption.AllDirectories)) { var cleanPath = path.Replace("\\", "/"); var relativePath = cleanPath.Replace(editorLuaScriptPath + "/", ""); var toPath = Path.Combine(toDir, relativePath) + ext; if (!Directory.Exists(Path.GetDirectoryName(toPath))) { Directory.CreateDirectory(Path.GetDirectoryName(toPath)); } File.Copy(cleanPath, toPath, true); if (OnCopyFile != null) { OnCopyFile(toPath); } luaCount++; } AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); Debug.Log(string.Format("[LuaModuleEditor]compile lua script count: {0}", luaCount)); } }
public void DrawAssetBundleUI() { GUILayout.BeginHorizontal("HelpBox"); EditorGUILayout.LabelField("== Assetbundle相关 =="); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("打包AB", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(30))) { BuildTools.BuildAllAssetBundles(); } if (GUILayout.Button("删除全部AB并重新打包", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(30))) { BuildTools.ReBuildAllAssetBundles(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("设置AB Name", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(30))) { BuildTools.MakeAssetBundleNames(); } if (GUILayout.Button("清空全部AB Name", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(30))) { BuildTools.ClearAssetBundleNames(); } if (GUILayout.Button("打开AB目录", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { var path = AppConfig.ProductRelPath + "/Bundles/" + KResourceModule.GetBuildPlatformName(); OpenFolder(path, true); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("清理冗余资源", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(30))) { BuildTools.CleanAssetBundlesRedundancies(); } GUILayout.EndHorizontal(); }
/// <summary> /// Call script of script path (relative) specify /// </summary> /// <param name="scriptRelativePath"></param> /// <returns></returns> public object CallScript(string scriptRelativePath) { Debuger.Assert(HasScript(scriptRelativePath), "Not exist Lua: " + scriptRelativePath); var scriptPath = GetScriptPath(scriptRelativePath); byte[] script; if (Log.IsUnityEditor) { script = File.ReadAllBytes(scriptPath); } else { script = KResourceModule.LoadSyncFromStreamingAssets(scriptPath); } var ret = ExecuteScript(script); return(ret); }
/// <summary> /// After Init Modules, coroutine /// </summary> /// <returns></returns> public override IEnumerator OnGameStart() { // Print AppConfigs Log.Info("======================================= Read Settings from C# ================================="); foreach (GameConfigSetting setting in GameConfigSettings.GetAll()) { Debug.Log(string.Format("C# Read Setting, Key: {0}, Value: {1}", setting.Id, setting.Value)); } yield return(null); Log.Info("======================================= Open Window 'Login' ================================="); UIModule.Instance.OpenWindow("Login", 888); // Test Load a scene in asset bundle SceneManager.LoadScene("Scene/TestScene/TestScene.unity"); // 开始加载我们的公告界面! //UIModule.Instance.OpenWindow("Billboard"); // 测试Collect函数,立即回收所有资源 var path = "ui/billboard.prefab"; var assetLoader = InstanceAssetLoader.Load(path); while (!assetLoader.IsCompleted) { yield return(null); } var assetLoader2 = InstanceAssetLoader.Load(path); while (!assetLoader2.IsCompleted) { yield return(null); } assetLoader2.Release(); assetLoader.Release(); KResourceModule.Collect(); }
void DrawBuildUI() { GUILayout.BeginHorizontal("HelpBox"); EditorGUILayout.LabelField("== 常用的功能键 =="); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("打PC版", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformWinBuild(); } if (GUILayout.Button("打Android包", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformAndroidBuild(); } if (GUILayout.Button("打IOS版", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformiOSBuild(); } if (GUILayout.Button("打开安装包目录", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { var path = KResourceModule.ProductRelPath + "/Apps/" + KResourceModule.GetBuildPlatformName(); var fullPath = Path.GetFullPath(path); if (Directory.Exists(fullPath) == false) { Log.Debug("{0} 目录不存在,定位到父目录。", fullPath); DirectoryInfo directoryInfo = new DirectoryInfo(fullPath); fullPath = directoryInfo.Parent.FullName; } Log.Debug("open: {0}", fullPath); System.Diagnostics.Process.Start("explorer.exe", fullPath); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.EndHorizontal(); }
/// <summary> /// After Init Modules, coroutine /// </summary> /// <returns></returns> public override IEnumerator OnGameStart() { // Print AppConfigs Log.Info("======================================= Read Settings from C# ================================="); foreach (GameConfigSetting setting in GameConfigSettings.GetAll()) { Debug.Log(string.Format("C# Read Setting, Key: {0}, Value: {1}", setting.Id, setting.Value)); } yield return(null); Log.Info("======================================= Open Window 'Login' ================================="); //UIModule.Instance.OpenWindow(wndName); // Test Load a scene in asset bundle //SceneLoader.Load("Scene/TestScene/TestScene.unity"); // 开始加载我们的公告界面! //UIModule.Instance.OpenWindow("Billboard"); // 测试Collect函数,立即回收所有资源 KResourceModule.Collect(); Messenger.Broadcast(GameDefine.MessageId_Local.GameStart.ToString()); }
public static void CreateSpriteAtlas(string src_path, string dst_path, string atlas_name, bool includeInBuild = true) { if (string.IsNullOrEmpty(src_path) || string.IsNullOrEmpty(dst_path) || string.IsNullOrEmpty(atlas_name)) { Log.LogError($"无法创建图集,路径为空. src_path={src_path} ,dst_path={dst_path} ,atlas_name={atlas_name}"); return; } if (!src_path.EndsWith("/")) { src_path = src_path + "/"; } var full_path = Path.GetFullPath(src_path); if (!Directory.Exists(full_path)) { Log.Info($"不创建图集,{src_path}下无atlas文件夹"); return; } var assets = Directory.GetFiles(full_path, "*.png"); //这里无法过滤两种类型 *.png|*.jpg if (assets == null || assets.Length == 0) { Log.Info($"{src_path}下无图片,不生成图集"); return; } SpriteAtlas spriteAtlas = new SpriteAtlas(); if (!dst_path.EndsWith("/")) { dst_path = dst_path + "/"; } if (!Directory.Exists(dst_path)) { Directory.CreateDirectory(dst_path); } AssetDatabase.CreateAsset(spriteAtlas, dst_path + atlas_name + ".spriteatlas"); foreach (var path in assets) { var t = src_path + Path.GetFileName(path); var o = AssetDatabase.LoadAssetAtPath <Sprite>(t); if (o != null) { SpriteAtlasExtensions.Add(spriteAtlas, new Object[] { o }); } } //TODO 根据平台设置图集格式 //EditorUserBuildSettings.activeBuildTarget var atlasSetting = spriteAtlas.GetPlatformSettings(KResourceModule.GetBuildPlatformName()); atlasSetting.maxTextureSize = 2048; atlasSetting.textureCompression = TextureImporterCompression.Compressed; atlasSetting.format = TextureImporterFormat.Automatic; spriteAtlas.SetIncludeInBuild(includeInBuild); spriteAtlas.SetPlatformSettings(atlasSetting); SpriteAtlasUtility.PackAtlases(new SpriteAtlas[] { spriteAtlas }, EditorUserBuildSettings.activeBuildTarget, false); AssetDatabase.SaveAssets(); Log.Info($"创建图集{spriteAtlas.name}完成,包含{spriteAtlas.spriteCount}个图片"); }
public static void OpenPersistentDataPath() { System.Diagnostics.Process.Start(KResourceModule.GetAppDataPath()); }
private IEnumerator CoLoad(string url, KResourceInAppPathType type, KAssetBundleLoaderMode loaderMode) { if (KResourceModule.GetResourceFullPath(url, out FullUrl, _inAppPathType)) { } else { if (Debug.isDebugBuild) { Logger.LogError("[KBytesLoader]Error Path: {0}", url); } OnFinish(null); } if (_inAppPathType == KResourceInAppPathType.PersistentAssetsPath) { Progress = .5f; Bytes = File.ReadAllBytes(FullUrl); } else if (_inAppPathType == KResourceInAppPathType.StreamingAssetsPath) { _wwwLoader = KWWWLoader.Load(FullUrl); while (!_wwwLoader.IsCompleted) { Progress = _wwwLoader.Progress / 2f; // 最多50%, 要算上Parser的嘛 yield return(null); } if (!_wwwLoader.IsSuccess) { //if (AssetBundlerLoaderErrorEvent != null) //{ // AssetBundlerLoaderErrorEvent(this); //} Logger.LogError("[KBytesLoader]Error Load WWW: {0}", url); OnFinish(null); yield break; } Bytes = _wwwLoader.Www.bytes; } else if (_inAppPathType == KResourceInAppPathType.ResourcesAssetsPath) // 使用Resources文件夹模式 { var pathExt = Path.GetExtension(FullUrl); // Resources.Load无需扩展名 var pathWithoutExt = FullUrl.Substring(0, FullUrl.Length - pathExt.Length); if (_loaderMode == KAssetBundleLoaderMode.ResourcesLoad) { var textAsset = Resources.Load <TextAsset>(pathWithoutExt); if (textAsset == null) { Logger.LogError("[KBytesLoader]Cannot Resources.Load from : {0}", pathWithoutExt); OnFinish(null); yield break; } Bytes = textAsset.bytes; Resources.UnloadAsset(textAsset); } else if (_loaderMode == KAssetBundleLoaderMode.ResourcesLoadAsync) { var loadReq = Resources.LoadAsync <TextAsset>(pathWithoutExt); while (!loadReq.isDone) { Progress = loadReq.progress / 2f; // 最多50%, 要算上Parser的嘛 } var loadAsset = loadReq.asset; var loadTextAsset = loadAsset as TextAsset; if (loadTextAsset == null) { Logger.LogError("[KBytesLoader]Error Resources.LoadAsync: {0}", url); OnFinish(null); yield break; } Bytes = loadTextAsset.bytes; Resources.UnloadAsset(loadTextAsset); } else { Logger.LogError("[KBytesLoader]Unvalid LoaderMode on Resources Load Mode: {0}", _loaderMode); OnFinish(null); yield break; } } else { Logger.LogError("[KBytesLoader]Error InAppPathType: {0}", KResourceModule.DefaultInAppPathType); OnFinish(null); yield break; } OnFinish(Bytes); }
public static void CleanAssetBundlesRedundancies() { var platformName = KResourceModule.GetBuildPlatformName(); var outputPath = GetExportPath(EditorUserBuildSettings.activeBuildTarget); var srcList = new List <string>(Directory.GetFiles(ResourcesBuildDir, "*.*", SearchOption.AllDirectories)); for (var i = srcList.Count - 1; i >= 0; i--) { if (srcList[i].EndsWith(".meta")) { srcList.RemoveAt(i); } else { srcList[i] = srcList[i].Replace(ResourcesBuildDir, "").ToLower(); } } var toListMap = new Dictionary <string, string>(); var toList = new List <string>(Directory.GetFiles(outputPath, "*.*", SearchOption.AllDirectories)); for (var i = toList.Count - 1; i >= 0; i--) { var filePath = toList[i]; if (toList[i].EndsWith((".meta")) || toList[i].EndsWith(".manifest")) { toList.RemoveAt(i); } else { var rName = toList[i].Replace(outputPath, ""); if (rName == platformName || // 排除AB 平台总索引文件, rName == (platformName + ".manifest") || rName == (platformName + ".meta") || rName == (platformName + ".manifest.meta")) { toList.RemoveAt(i); } else { // 去掉扩展名,因为AssetBundle额外扩展名 toList[i] = Path.ChangeExtension(rName, ""); // 会留下最后句点 toList[i] = toList[i].Substring(0, toList[i].Length - 1); // 去掉句点 toListMap[toList[i]] = filePath; } } } // 删文件和manifest for (var i = 0; i < toList.Count; i++) { if (!srcList.Contains(toList[i])) { var filePath = toListMap[toList[i]]; var manifestPath = filePath + ".manifest"; File.Delete(filePath); Debug.LogWarning("Delete... " + filePath); if (File.Exists(manifestPath)) { File.Delete(manifestPath); Debug.LogWarning("Delete... " + manifestPath); } } } }
/// <summary> /// whether the script file exists? /// </summary> /// <param name="scriptRelativePath"></param> /// <returns></returns> public bool HasScript(string scriptRelativePath) { var scriptPath = GetScriptPath(scriptRelativePath); return(KResourceModule.IsResourceExist(scriptPath)); }
IEnumerator Start() { //KGameSettings.Instance.InitAction += OnGameSettingsInit; var engine = KEngine.AppEngine.New( gameObject, null, new IModuleInitable[] { //KGameSettings.Instance, // UIModule.Instance, }); while (!engine.IsInited) { yield return(null); } var uiName = "DemoHome"; UIModule.Instance.OpenWindow(uiName); Debug.Log("[SettingModule]Table: " + string.Join(",", ExampleSettings.TabFilePaths)); foreach (ExampleSetting exampleInfo in ExampleSettings.GetAll()) { Debug.Log(string.Format("Name: {0}", exampleInfo.Name)); Debug.Log(string.Format("Number: {0}", exampleInfo.Number)); } var info = ExampleSettings.Get("A_1024"); Debuger.Assert(info.Name == "Test1"); var info2 = SubdirExample2Settings.Get(2); Debuger.Assert(info2.Name == "Test2"); var info3 = AppConfigSettings.Get("Test.Cat1"); Debuger.Assert(info3.Value == "Cat1"); ExampleSettings.OnReload = () => { var reloadedInfo = ExampleSettings.Get("C_9888"); Log.Info("Reload ExampleInfos! Now info: {0} -> {1}", "C_9888", reloadedInfo.Name); }; Log.Info("Start reading streamingAssets Test..."); //打开或获取UI实例,并设置UI中的值 UIModule.Instance.CallUI(uiName, (ui, args) => { var tip = string.Format("Reading from streamingAssets, content: {0}", Encoding.UTF8.GetString(KResourceModule.LoadSyncFromStreamingAssets("TestFile.txt"))); var demoHome = ui as KUIDemoHome; demoHome.TipLabel.text += tip; // Do some UI stuff }); }
/// <summary> /// 对比两个filelist,把不相同的添加到下载列表中 /// </summary> /// <param name="local"></param> /// <param name="remote"></param> void GetDownloadFromFilelist(string local, string remote) { if (string.IsNullOrEmpty(local)) { //TODO filelist异常 Log.LogError("本地filelist为空"); return; } if (string.IsNullOrEmpty(remote)) { //TODO filelist异常 Log.LogError("远程filelist为空"); return; } Dictionary <string, FileList> localDict = new Dictionary <string, FileList>(); using (StringReader reader = new StringReader(local)) { while (true) { var line = reader.ReadLine(); if (line == null) { break; } var file = ParseToFileList(line); if (file != null) { localDict[file.path] = file; } } } string abDirName = AppConfig.StreamingBundlesFolderName + "/" + KResourceModule.GetBuildPlatformName() + "/"; var savePath = KResourceModule.AppDataPath + abDirName; using (StringReader reader = new StringReader(remote)) { while (true) { var line = reader.ReadLine(); if (line == null) { break; } var file = ParseToFileList(line); if (file != null) { var realPath = savePath + file.path; if (File.Exists(realPath) && KTool.MD5_File(realPath) == file.md5) { filelistBuilder.AppendLine(file.ToFilelistFormat()); Log.LogToFile($"文件存在:{file.path},且md5一致,跳过下载"); continue; } if (localDict.TryGetValue(file.path, out FileList exist)) { if (exist.md5 != file.md5 || exist.size != file.size) { var newFile = new FileList() { path = abDirName + file.path, md5 = file.md5, size = file.size }; downloadFiles.Add(newFile); downloadTotalSize += file.size; } else { filelistBuilder.AppendLine(file.ToFilelistFormat()); } } else { var newFile = new FileList() { path = abDirName + file.path, md5 = file.md5, size = file.size }; downloadFiles.Add(newFile); downloadTotalSize += file.size; } } } } }
private List <string> BuildedList = new List <string>(); // 累计Build了多少次,用于版本控制时用的 // Prefab Asset打包版本號記錄 public static string GetBuildVersionTab() { return(Application.dataPath + "/../" + KEngineDef.ResourcesBuildInfosDir + "/ArtBuildResource_" + KResourceModule.GetBuildPlatformName() + ".txt"); }
/// <summary> /// Unity Resources.Load setting file in Resources folder /// </summary> /// <param name="path"></param> /// <returns></returns> protected override string LoadSetting(string path) { byte[] fileContent = KResourceModule.LoadAssetsSync(GetSettingFilePath(path)); return(Encoding.UTF8.GetString(fileContent)); }
private IEnumerator _Init(string path, string assetName, KAssetBundleLoaderMode loaderMode) { IsLoadAssetBundle = KEngine.AppEngine.GetConfig("IsLoadAssetBundle").ToInt32() != 0; AssetInBundleName = assetName; UnityEngine.Object getAsset = null; if (!IsLoadAssetBundle) { string extension = System.IO.Path.GetExtension(path); path = path.Substring(0, path.Length - extension.Length); // remove extensions getAsset = Resources.Load <UnityEngine.Object>(path); if (getAsset == null) { Logger.LogError("Asset is NULL(from Resources Folder): {0}", path); } OnFinish(getAsset); } else { _bundleLoader = KAssetBundleLoader.Load(path, null, loaderMode); while (!_bundleLoader.IsCompleted) { if (IsReadyDisposed) // 中途释放 { _bundleLoader.Release(); OnFinish(null); yield break; } yield return(null); } if (!_bundleLoader.IsSuccess) { Logger.LogError("[KAssetFileLoader]Load BundleLoader Failed(Error) when Finished: {0}", path); _bundleLoader.Release(); OnFinish(null); yield break; } var assetBundle = _bundleLoader.Bundle; System.DateTime beginTime = System.DateTime.Now; if (AssetInBundleName == null) { // 经过AddWatch调试,.mainAsset这个getter第一次执行时特别久,要做序列化 //AssetBundleRequest request = assetBundle.LoadAsync("", typeof(Object));// mainAsset //while (!request.isDone) //{ // yield return null; //} try { Logger.Assert(getAsset = assetBundle.mainAsset); } catch { Logger.LogError("[OnAssetBundleLoaded:mainAsset]{0}", path); } } else { // TODO: 未测试过这几行!~~ AssetBundleRequest request = assetBundle.LoadAsync(AssetInBundleName, typeof(Object)); while (!request.isDone) { yield return(null); } getAsset = request.asset; } KResourceModule.LogLoadTime("AssetFileBridge", path, beginTime); if (getAsset == null) { Logger.LogError("Asset is NULL: {0}", path); } _bundleLoader.Release(); // 释放Bundle(WebStream) } if (Application.isEditor) { if (getAsset != null) { KResoourceLoadedAssetDebugger.Create(getAsset.GetType().Name, Url, getAsset as UnityEngine.Object); } } if (getAsset != null) { // 更名~ 注明来源asset bundle 带有类型 getAsset.name = string.Format("{0}~{1}", getAsset, Url); } OnFinish(getAsset); }
public IEnumerator CheckDownload() { ClearData(); var loadingPanel = UIModule.Instance.GetOrCreateUI <LoadingPanel>(); loadingPanel.SetProgress(I18N.Get("download_check")); loadingPanel.DisPlay(true); string url = AppConfig.resUrl + AppConfig.VersionTxtName; Log.LogToFile($"读取远程version.txt:{url}"); var loader = KWWWLoader.Load(url); while (!loader.IsCompleted) { yield return(null); } if (!loader.IsError) { ParseText(loader.Www.text, remoteVersion); remoteVersion.TryGetValue("filelist.txt", out filelistVersion); } else { ErrorType = UpdateErrorType.RemoteVersionError; yield break; } url = KResourceModule.GetResourceFullPath(AppConfig.VersionTxtName, false); Log.LogToFile($"读取本地version.txt:{url}"); loader = KWWWLoader.Load(url); while (!loader.IsCompleted) { yield return(null); } if (!loader.IsError) { ParseText(loader.Www.text, localVersion); } else { ErrorType = UpdateErrorType.LocalVersionError; yield break; } loader.Dispose(); loader = null; CompareVersion("lua.zip"); CompareVersion("setting.zip"); bool filelistSame = CompareVersion("filelist.txt", false); if (filelistSame == false) { //对比ab列表 string remote_filelist = null; url = AppConfig.resUrl + AppConfig.FilelistPath; loader = KWWWLoader.Load(url); while (!loader.IsCompleted) { yield return(null); } if (!loader.IsError) { remote_filelist = loader.Www.text; } else { ErrorType = UpdateErrorType.FilelistnError; } url = KResourceModule.GetResourceFullPath(AppConfig.FilelistPath, false); loader = KWWWLoader.Load(url); while (!loader.IsCompleted) { yield return(null); } //开始对比两个filelist if (!loader.IsError) { GetDownloadFromFilelist(loader.Www.text, remote_filelist); } else { ErrorType = UpdateErrorType.LocalFilelistnError; } } if (downloadFiles.Count > 0) { var panel = UIModule.Instance.GetOrCreateUI <KUIMsgBox>(); UIMsgBoxInfo info = new UIMsgBoxInfo().GetDefalut(I18N.Get("download_msg", KTool.FormatFileSize(downloadTotalSize)), strCancel: I18N.Get("common_skip")); info.OkCallback = () => { Game.Instance.StartCoroutine(StartUpdate()); }; info.CancelCallback = IngoreDownload; panel.info = info; panel.DisPlay(true); } else { Log.LogToFile($"本次启动无资源更新,跳过下载"); ClearData(); DownloadFinish = true; } }
/// <summary> /// 协和加载Assetbundle,加载完后执行callback /// </summary> /// <param name="url">资源的url</param> /// <param name="callback"></param> /// <param name="callbackArgs"></param> /// <returns></returns> private IEnumerator CoLoad(string url) { KResourceModule.LogRequest("WWW", url); System.DateTime beginTime = System.DateTime.Now; // 潜规则:不用LoadFromCache~它只能用在.assetBundle Www = new WWW(url); BeginLoadTime = Time.time; WWWLoadingCount++; //设置AssetBundle解压缩线程的优先级 Www.threadPriority = Application.backgroundLoadingPriority; // 取用全局的加载优先速度 while (!Www.isDone) { Progress = Www.progress; yield return(null); } yield return(Www); WWWLoadingCount--; Progress = 1; if (IsReadyDisposed) { Logger.LogError("[KWWWLoader]Too early release: {0}", url); OnFinish(null); yield break; } if (!string.IsNullOrEmpty(Www.error)) { if (Application.platform == RuntimePlatform.Android) { // TODO: Android下的错误可能是因为文件不存在! } string fileProtocol = KResourceModule.GetFileProtocol(); if (url.StartsWith(fileProtocol)) { string fileRealPath = url.Replace(fileProtocol, ""); Logger.LogError("File {0} Exist State: {1}", fileRealPath, System.IO.File.Exists(fileRealPath)); } Logger.LogError("[KWWWLoader:Error]{0} {1}", Www.error, url); OnFinish(null); yield break; } else { KResourceModule.LogLoadTime("WWW", url, beginTime); if (WWWFinishCallback != null) { WWWFinishCallback(url); } Desc = string.Format("{0}K", Www.bytes.Length / 1024f); OnFinish(Www); } // 预防WWW加载器永不反初始化, 造成内存泄露~ if (Application.isEditor) { while (GetCount <KWWWLoader>() > 0) { yield return(null); } yield return(new WaitForSeconds(5f)); while (Debug.isDebugBuild && !IsReadyDisposed) { Logger.LogError("[KWWWLoader]Not Disposed Yet! : {0}", this.Url); yield return(null); } } }
void DrawBuildUI() { GUILayout.BeginHorizontal("HelpBox"); EditorGUILayout.LabelField("== 生成安装包 =="); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("打开安装包目录", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { var path = AppConfig.ProductRelPath + "/Apps/" + KResourceModule.GetBuildPlatformName(); OpenFolder(path, true); } if (GUILayout.Button("生成Version.txt", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { string batPath = null; if (!File.Exists(AppConfig.VersionTextPath)) { var platform = KResourceModule.GetBuildPlatformName(); //执行bat batPath = $"{AppConfig.BuildScriptPath}/生成filelist-{platform}.bat"; KTool.ExecuteCommand(batPath); //ps.执行py传的参数有些错误,所以通过cmd来执行py // var abPath = KResourceModule.EditorProductFullPath+"/Bundles/"+platform; // BuildTools.ExecutePyFile(pyPath + "/gen_filelist.py",$"{pyPath} {abPath} {platform}"); } if (!File.Exists(AppConfig.VersionTextPath)) { Log.LogError($"未找到{AppConfig.VersionTextPath},请查看报错信息或手动执行脚本{batPath}"); return; } var dstPath = KResourceModule.AppDataPath + AppConfig.VersionTxtName; if (File.Exists(dstPath)) { File.Delete(dstPath); } File.Copy(AppConfig.VersionTextPath, dstPath); Log.Info($"文件拷贝成功,{AppConfig.VersionTextPath}->{dstPath}"); } if (GUILayout.Button("打包脚本目录", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { OpenFolder(AppConfig.BuildScriptPath, true); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("打PC版", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformWinReleaseBuild(); } if (GUILayout.Button("打PC版-Dev", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformWinBuild(); } if (GUILayout.Button("打PC版-IL2CPP", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformWinIL2CPPBuild(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("打Android版", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformAndroidBuild(); } if (GUILayout.Button("Android-IL2CPP", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformAndroidIL2CPPBuild(); } if (GUILayout.Button("打IOS版", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformiOSBuild(); } GUILayout.EndHorizontal(); }
void DrawBuildUI() { GUILayout.BeginHorizontal("HelpBox"); EditorGUILayout.LabelField("== 生成安装包 =="); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("打开安装包目录", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { var path = AppConfig.ProductRelPath + "/Apps/" + KResourceModule.GetBuildPlatformName(); OpenFolder(path); } if (GUILayout.Button("下载更新调试", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { if (!File.Exists(AppConfig.VersionTextPath)) { var pyPath = Path.GetDirectoryName(Path.GetFullPath(Application.dataPath + "/../../build_tools/")); var platform = KResourceModule.GetBuildPlatformName(); //执行bat var path = $"{pyPath}/生成filelist-{platform}.bat"; KTool.ExecuteCommand(path); //执行py传的参数有些错误 // var abPath = KResourceModule.ProductPathWithoutFileProtocol+"/Bundles/"+platform; // BuildTools.ExecutePyFile(pyPath + "/gen_filelist.py",$"{pyPath} {abPath} {platform}"); } if (!File.Exists(AppConfig.VersionTextPath)) { Log.LogError($"未生成filelist,请再试一次或手动执行py脚本"); return; } var dstPath = KResourceModule.AppDataPath + AppConfig.VersionTxtName; if (File.Exists(dstPath)) { File.Delete(dstPath); } File.Copy(AppConfig.VersionTextPath, dstPath); Log.Info($"文件拷贝成功,{AppConfig.VersionTextPath}->{dstPath}"); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("打PC版", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformWinReleaseBuild(); } if (GUILayout.Button("打PC版-Dev", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformWinBuild(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("打Android版", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformAndroidBuild(); } if (GUILayout.Button("打IOS版", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(20))) { KAutoBuilder.PerformiOSBuild(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.EndHorizontal(); }