public static void SymbolLinkResource() { KSymbolLinkHelper.DeleteAllLinks(AssetBundlesLinkPath); var exportPath = GetResourceExportPath(); var linkPath = GetABLinkPath(); KSymbolLinkHelper.SymbolLinkFolder(exportPath, linkPath); //NOTE 特别无解,无法同步link这两个目录,使用协程处理后目录内容是空,如果2018及以下版本无EditorCoroutine使用脚本进行link /*Log.Info("Add Symbol Link Assetbundle."); * ins = new object(); * EditorCoroutineUtility.StartCoroutine(LinkLua(), ins); * Log.Info("Add Symbol Link Lua."); * EditorCoroutineUtility.StartCoroutine(LinkSettings(), ins); * Log.Info("Add Symbol Link Settings.");*/ var linkFile = Application.dataPath + "/../AssetLink.sh"; if (System.Environment.OSVersion.ToString().Contains("Windows")) { linkFile = Application.dataPath + "/../AssetLink.bat"; } KTool.ExecuteFile(linkFile); var dstPath = Application.streamingAssetsPath + "/" + AppConfig.VersionTxtName; if (File.Exists(dstPath)) { File.Delete(dstPath); } File.Copy(AppConfig.VersionTextPath, dstPath); Log.Info($"拷贝version.txt完成,File.Exists:{File.Exists(dstPath)}"); AssetDatabase.Refresh(); }
public XUIMidMsgAnimator PoolGet() { XUIMidMsgAnimator msgInstance = null; if (m_MsgTempllatePool.Count > 0) { msgInstance = m_MsgTempllatePool.Pop(); } if (msgInstance == null) { GameObject newGameObj = GameObject.Instantiate(MsgTemplate) as GameObject; msgInstance = newGameObj.GetComponent <XUIMidMsgAnimator>(); if (msgInstance == null) { msgInstance = newGameObj.AddComponent <XUIMidMsgAnimator>(); } msgInstance.transform.SetParent(this.transform); msgInstance.UICtrler = this; } KTool.ResetLocalTransform(msgInstance.transform); msgInstance.gameObject.SetActive(true); return(msgInstance); }
/// <summary> /// 每秒计算下载速度,每帧更新进度条 /// </summary> void OnUpdateProgress() { long downloadFinish = (long)(downloadTemp + downloadNow); totalProgress = KTool.GetPercent(downloadFinish, downloadTotalSize) - zipPercent; totalProgress = Mathf.Max(totalProgress, 0.0f); if (Time.time > last_time) { last_time = Time.time + 1.0f; time_per = 0; // 下载速度 = 前1秒下载量 / 1s ,总下载=下载中 + 已下载 speed = downloadFinish - downloadLastSecond; speed = (long)Mathf.Max(speed, 0); remainTime = KTool.GetPercent(downloadTotalSize - downloadFinish, speed); downloadLastSecond = downloadFinish; lastTotalProgress = totalProgress; } var panel = UIModule.Instance.GetExistUI <LoadingPanel>(); if (panel != null) { string strSize = $"{KTool.FormatFileSize(downloadFinish)}/{KTool.FormatFileSize(downloadTotalSize)}"; string strSpeed = (speed / 1024f).ToString("0.##"); time_per += Time.deltaTime; var progress = Mathf.Lerp(lastTotalProgress, totalProgress, time_per); panel.SetProgress(I18N.Get("download_speed", strSize, strSpeed, KTool.HumanizeTimeString((int)remainTime)), progress); } }
private bool CompareVersion(string verName, bool needDownload = true) { remoteVersion.TryGetValue(verName, out FileList remote_ver); localVersion.TryGetValue(verName, out FileList local_ver); bool isSame = remote_ver == local_ver; Log.LogToFile($"{verName}版本是否相同:{isSame} ,远程版本号:{remote_ver?.md5} ,本地版本号:{local_ver?.md5}"); if (isSame == false) { var realPath = KResourceModule.AppDataPath + verName; if (File.Exists(realPath) && remote_ver != null && KTool.MD5_File(realPath) == remote_ver.md5) { Log.LogToFile($"文件存在:{verName},且md5一致,跳过下载"); return(isSame); } if (!needDownload) { return(isSame); } downloadFiles.Add(remote_ver); if (verName.Contains("lua")) { needUnpackLua = true; } if (verName.Contains("setting")) { needUnpackSetting = true; } downloadTotalSize += remote_ver.size; } return(isSame); }
public UIModule() { var configUiBridge = AppEngine.GetConfig("KEngine.UI", "UIModuleBridge"); if (!string.IsNullOrEmpty(configUiBridge)) { var uiBridgeTypeName = string.Format("{0}", configUiBridge); var uiBridgeType = KTool.FindType(uiBridgeTypeName); if (uiBridgeType != null) { UiBridge = Activator.CreateInstance(uiBridgeType) as IUIBridge; Log.Debug("Use UI Bridge: {0}", uiBridgeType); } else { Log.Error("Cannot find UIBridge Type: {0}", uiBridgeTypeName); } } if (UiBridge == null) { UiBridge = new UGUIBridge(); } UiBridge.InitBridge(); }
public bool Contains(string str) { var findStr = str; if (_isMD5) { findStr = KTool.MD5_16bit(str); } return(_hashSet.Contains(findStr)); }
public static CVersionNumber Parse(string verStr) { var verArgs = KTool.Split <string>(verStr, '.'); return(new CVersionNumber { Major = verArgs.Count >= 1 ? verArgs[0].ToInt32() : 0, Minor = verArgs.Count >= 2 ? verArgs[1].ToInt32() : 0, Build = verArgs.Count >= 3 ? verArgs[2].ToInt32() : 0, Flag = verArgs.Count >= 4 ? verArgs[3] : "" }); }
/// <summary> /// 标记一个路径为打包 /// </summary> public void MarkBuildVersion(params string[] sourceFiles) { if (sourceFiles == null || sourceFiles.Length == 0) { return; } foreach (string file in sourceFiles) { //StoreBuildVersion[file] = GetAssetVersion(file); BuildRecord theRecord; var nowMd5 = KTool.MD5_File(file); if (!StoreBuildVersion.TryGetValue(file, out theRecord)) { theRecord = new BuildRecord(); theRecord.Mark(nowMd5); } else { if (nowMd5 != theRecord.MD5) // 只有改变时才会mark,所以可能会出现情况,rebuild时,change count不改变 { theRecord.Mark(nowMd5); } } StoreBuildVersion[file] = InstanceBuildVersion[file] = theRecord; // ensure in dict string metaFile = file + ".meta"; if (File.Exists(metaFile)) { BuildRecord theMetaRecord; var nowMetaMd5 = KTool.MD5_File(metaFile); if (!StoreBuildVersion.TryGetValue(metaFile, out theMetaRecord)) { theMetaRecord = new BuildRecord(); theMetaRecord.Mark(nowMetaMd5); } else { if (nowMetaMd5 != theMetaRecord.MD5) { theMetaRecord.Mark(nowMetaMd5); } } StoreBuildVersion[metaFile] = InstanceBuildVersion[metaFile] = theMetaRecord; // ensure in dict } // meta不记录 Current.BuildedList.Add(file); } }
void Start() { if (UseLangId && string.IsNullOrEmpty(text)) { if (!string.IsNullOrEmpty(LangId)) { text = I18N.Get(LangId, LangParams); } else { Log.LogError($"{KTool.GetRootPathName(this.transform)},lang id is null"); } } }
/// <summary> /// 获取波浪随机数的最大最小 /// </summary> /// <param name="str"></param> /// <returns></returns> public static FromToNumber ParseMinMaxNumber(string str) { var rangeArr = KTool.Split <float>(str, '~', '-'); var number = new FromToNumber(); if (rangeArr.Count > 0) { number.From = rangeArr[0]; } if (rangeArr.Count > 1) { number.To = rangeArr[1]; } return(number); }
public bool Add(string str) { var setStr = str.Trim(); if (_isMD5) { setStr = KTool.MD5_16bit(str); } if (_hashSet.Add(setStr)) { _writer.WriteLine(setStr); return(true); } return(false); }
/// <summary> /// 检查是否需要build, /// 文件,要进行MD5校验 /// </summary> /// <param name="filePath"></param> /// <param name="isFile"></param> /// <param name="log"></param> /// <returns></returns> private bool DoCheckBuild(string filePath, bool log = true) { // #if UNITY_5 var currentScene = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().path; // #else // var currentScene = EditorApplication.currentScene; // #endif BuildRecord assetMd5; if (!File.Exists(filePath)) { if (log) { Log.Error("[DoCheckBuild]Not Found 无法找到文件 {0}", filePath); } if (filePath.Contains("unity_builtin_extra")) { Log.Error( "[DoCheckBuild]Find unity_builtin_extra resource to build!! Please check it! current scene: {0}", currentScene); } return(false); } if (InstanceBuildVersion.ContainsKey(filePath)) // 本次打包已经处理过,就不用重复处理了 { return(false); } if (_isRebuild) // 所有rebuild,不用判断,直接需要build, 保留change count的正确性 { return(true); } // 不存在记录,则需要打包吧 if (!DoCheckExistRecord(filePath, out assetMd5)) { return(true); } if (KTool.MD5_File(filePath) != assetMd5.MD5) { return(true); // different } return(false); }
protected static Transform GetParent(string bigType, string smallType) { var uri = GetUri(bigType, smallType); Transform theParent; if (!Parents.TryGetValue(uri, out theParent)) { var bigTypeObjName = string.Format("__{0}__", bigType); var bigTypeObj = GameObject.Find(bigTypeObjName) ?? new GameObject(bigTypeObjName); GameObject.DontDestroyOnLoad(bigTypeObj); theParent = new GameObject(smallType).transform; KTool.SetChild(theParent, bigTypeObj.transform); Parents[uri] = theParent; } return(theParent); }
/// <summary> /// 删除硬链接目录 /// </summary> /// <param name="linkPath"></param> public static void DeleteLink(string linkPath) { var os = Environment.OSVersion; if (os.ToString().Contains("Windows")) { KTool.ExecuteCommand(String.Format("rmdir \"{0}\"", linkPath)); } else if (os.ToString().Contains("Unix")) { KTool.ExecuteCommand(String.Format("rm -Rf \"{0}\"", linkPath)); } else { Debug.LogError(String.Format("[SymbolLinkFolder]Error on OS: {0}", os.ToString())); } }
/// <summary> /// 检查是否需要build, /// 文件,要进行MD5校验 /// </summary> /// <param name="filePath"></param> /// <param name="isFile"></param> /// <param name="log"></param> /// <returns></returns> private bool DoCheckBuild(string filePath, bool log = true) { BuildRecord assetMd5; if (!File.Exists(filePath)) { if (log) { Logger.LogError("[DoCheckBuild]Not Found 无法找到文件 {0}", filePath); } if (filePath.Contains("unity_builtin_extra")) { Logger.LogError( "[DoCheckBuild]Find unity_builtin_extra resource to build!! Please check it! current scene: {0}", EditorApplication.currentScene); } return(false); } if (InstanceBuildVersion.ContainsKey(filePath)) // 本次打包已经处理过,就不用重复处理了 { return(false); } if (_isRebuild) // 所有rebuild,不用判断,直接需要build, 保留change count的正确性 { return(true); } if (!StoreBuildVersion.TryGetValue(filePath, out assetMd5)) { return(true); } if (KTool.MD5_File(filePath) != assetMd5.MD5) { return(true); // different } return(false); }
public static void SymbolLinkFolder(string srcFolderPath, string targetPath) { var os = Environment.OSVersion; if (os.ToString().Contains("Windows")) { KTool.ExecuteCommand(String.Format("mklink /J \"{0}\" \"{1}\"", targetPath, srcFolderPath)); } else if (os.ToString().Contains("Unix")) { var fullPath = Path.GetFullPath(targetPath); if (fullPath.EndsWith("/")) { fullPath = fullPath.Substring(0, fullPath.Length - 1); fullPath = Path.GetDirectoryName(fullPath); } KTool.ExecuteCommand(String.Format("ln -s {0} {1}", Path.GetFullPath(srcFolderPath), fullPath)); } else { Debug.LogError(String.Format("[SymbolLinkFolder]Error on OS: {0}", os.ToString())); } }
/// <summary> /// 设置某个物件,在指定调试组下 /// </summary> /// <param name="bigType"></param> /// <param name="smallType"></param> /// <param name="obj"></param> public static void SetParent(string bigType, string smallType, GameObject obj) { var uri = GetUri(bigType, smallType); Transform theParent = GetParent(bigType, smallType); int typeCount; if (!Counts.TryGetValue(uri, out typeCount)) { Counts[uri] = 0; } typeCount = ++Counts[uri]; try { KTool.SetChild(obj, theParent.gameObject); } catch (Exception e) { Logger.LogError(string.Format("[SetParent]{0}->{1}->{2}", bigType, smallType, e.Message)); } theParent.gameObject.name = GetNameWithCount(smallType, typeCount); }
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(); }
// 加载材质的图片, 协程等待 private IEnumerator CoGenerateMaterial(string matPath, KSerializeMaterial sMat) { // 纹理全部加载完成后到这里 //if (!CachedMaterials.TryGetValue(matPath, out mat)) { var shaderLoader = KShaderLoader.Load(sMat.ShaderPath); while (!shaderLoader.IsCompleted) { yield return(null); } var shader = shaderLoader.ShaderAsset; if (shader == null) { shader = KTool.FindShader(sMat.ShaderName); Logger.LogWarning("无法加载Shader资源: {0}, 使用Shaders.Find代替", sMat.ShaderName); if (shader == null) { Logger.LogWarning("找不到Shader: {0}, 使用Diffuse临时代替", sMat.ShaderName); shader = KTool.FindShader("Diffuse"); } } Debuger.Assert(shader); Mat = new Material(shader); Mat.name = sMat.MaterialName; //CachedMaterials[matPath] = mat; foreach (KSerializeMaterialProperty shaderProp in sMat.Props) { switch (shaderProp.Type) { case KSerializeMaterialProperty.ShaderType.Texture: Vector2 tiling; Vector2 offset; var texturePath = ParseMaterialStr(shaderProp.PropValue, out tiling, out offset); if (TextureLoaders == null) { TextureLoaders = new List <KTextureLoader>(); } var texLoader = KTextureLoader.Load(texturePath); TextureLoaders.Add(texLoader); while (!texLoader.IsCompleted) { yield return(null); } var tex = texLoader.Asset; if (tex == null) { Logger.LogError("找不到纹理: {0}", texturePath); } else { _SetMatTex(Mat, shaderProp.PropName, tex, tiling, offset); } break; case KSerializeMaterialProperty.ShaderType.Color: _SetMatColor(Mat, shaderProp.PropName, shaderProp.PropValue); break; case KSerializeMaterialProperty.ShaderType.Range: _SetMatRange(Mat, shaderProp.PropName, shaderProp.PropValue); break; case KSerializeMaterialProperty.ShaderType.Vector: _SetMatVector(Mat, shaderProp.PropName, shaderProp.PropValue); break; case KSerializeMaterialProperty.ShaderType.RenderTexture: // RenderTextures, 不处理, 一般用在水,Water脚本会自动生成 break; } } } }
public static void CreateNewUI() { #if UNITY_5 || UNITY_2017_1_OR_NEWER var currentScene = EditorSceneManager.GetActiveScene().path; #else var currentScene = EditorApplication.currentScene; #endif GameObject mainCamera = GameObject.Find("Main Camera"); if (mainCamera != null) { GameObject.DestroyImmediate(mainCamera); } var uiName = Path.GetFileNameWithoutExtension(currentScene); if (String.IsNullOrEmpty(uiName) || GameObject.Find(uiName) != null) // default use scene name, if exist create random name { uiName = "NewUI_" + Path.GetRandomFileName(); } GameObject uiObj = new GameObject(uiName); uiObj.layer = (int)UnityLayerDef.UI; uiObj.AddComponent <UIWindowAsset>(); var uiPanel = new GameObject("Image").AddComponent <Image>(); uiPanel.transform.parent = uiObj.transform; KTool.ResetLocalTransform(uiPanel.transform); var canvas = uiObj.AddComponent <Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; uiObj.AddComponent <CanvasScaler>(); uiObj.AddComponent <GraphicRaycaster>(); if (GameObject.Find("EventSystem") == null) { var evtSystemObj = new GameObject("EventSystem"); evtSystemObj.AddComponent <EventSystem>(); evtSystemObj.AddComponent <StandaloneInputModule>(); #if UNITY_4 evtSystemObj.AddComponent <TouchInputModule>(); #endif } if (GameObject.Find("Camera") == null) { GameObject cameraObj = new GameObject("Camera"); cameraObj.layer = (int)UnityLayerDef.UI; Camera camera = cameraObj.AddComponent <Camera>(); camera.clearFlags = CameraClearFlags.Skybox; camera.depth = 0; camera.backgroundColor = Color.grey; camera.cullingMask = 1 << (int)UnityLayerDef.UI; camera.orthographicSize = 1f; camera.orthographic = true; camera.nearClipPlane = -2f; camera.farClipPlane = 2f; camera.gameObject.AddComponent <AudioListener>(); } Selection.activeGameObject = uiObj; }
public static void CreateNewUI(PanelType panelType) { #if UNITY_5 || UNITY_2017_1_OR_NEWER var currentScene = EditorSceneManager.GetActiveScene().path; #else var currentScene = EditorApplication.currentScene; #endif GameObject mainCamera = GameObject.Find("Main Camera"); if (mainCamera != null) { GameObject.DestroyImmediate(mainCamera); } var uiName = Path.GetFileNameWithoutExtension(currentScene); if (string.IsNullOrEmpty(uiName) || GameObject.Find(uiName) != null) // default use scene name, if exist create random name { uiName = "UI" + Path.GetRandomFileName(); } GameObject uiObj = new GameObject(uiName); uiObj.layer = (int)UnityLayerDef.UI; var windowAsset = uiObj.AddComponent <UIWindowAsset>(); windowAsset.IsUIEditor = true; windowAsset.PanelType = panelType; if (panelType != PanelType.NormalUI) { windowAsset.MoneyBar = MoneyBarType.None; windowAsset.IsShowTabBar = false; windowAsset.TabBarId = 0; } var uiPanel = new GameObject("Image").AddComponent <Image>(); uiPanel.transform.SetParent(uiObj.transform); KTool.ResetLocalTransform(uiPanel.transform); var canvas = uiObj.AddComponent <Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceCamera; CanvasScaler canvasScaler = uiObj.AddComponent <CanvasScaler>(); uiObj.AddComponent <GraphicRaycaster>(); canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; canvasScaler.referenceResolution = AppConfig.UIResolution; canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.Expand; if (GameObject.Find("EventSystem") == null) { var evtSystemObj = new GameObject("EventSystem"); evtSystemObj.AddComponent <EventSystem>(); evtSystemObj.AddComponent <StandaloneInputModule>(); #if UNITY_4 evtSystemObj.AddComponent <TouchInputModule>(); #endif } Camera camera; var go = GameObject.Find("UICamera"); if (go == null) { GameObject cameraObj = new GameObject("UICamera"); cameraObj.layer = (int)UnityLayerDef.UI; camera = cameraObj.AddComponent <Camera>(); camera.clearFlags = CameraClearFlags.Skybox; camera.depth = 0; camera.backgroundColor = Color.grey; camera.cullingMask = 1 << (int)UnityLayerDef.UI; camera.orthographicSize = 1f; camera.orthographic = true; camera.nearClipPlane = 0.3f; camera.farClipPlane = 1000f; camera.gameObject.AddComponent <AudioListener>(); } else { camera = go.GetComponent <Camera>(); } canvas.worldCamera = camera; Selection.activeGameObject = uiObj; }
private void Save() { Prefs.SetKey("ActionRecords", KTool.DictToSplitStr(_records)); _isDirty = false; }
private void Init() { var str = Prefs.GetKey("ActionRecords") ?? ""; _records = KTool.SplitToDict <string, int>(str); }
public void ReadFromTab(Type type, ref CBaseInfo newT, IKTabReadble tabFile, int row) { if (Debug.isDebugBuild) { Debuger.Assert(typeof(CBaseInfo).IsAssignableFrom(type)); } // 缓存字段Field, 每个Type只反射一次! LinkedList <FieldInfo> okFields; if (!CacheTypeFields.TryGetValue(type, out okFields)) { okFields = CacheTypeFields[type] = new LinkedList <FieldInfo>(); var allFields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo field in allFields) { if (field.Name.StartsWith("_") || field.IsInitOnly) // 筛掉_ 和 readonly { continue; } if (!tabFile.HasColumn(field.Name)) { if (Debug.isDebugBuild) { Logger.LogError("表{0} 找不到表头{1}", type.Name, field.Name); } continue; } okFields.AddLast(field); } } // 读字段 foreach (var field in okFields) { var fieldName = field.Name; var fieldType = field.FieldType; object value; if (fieldType == typeof(int)) { value = tabFile.GetInteger(row, fieldName); } else if (fieldType == typeof(long)) { value = (long)tabFile.GetInteger(row, fieldName); } else if (fieldType == typeof(string)) { value = tabFile.GetString(row, fieldName).Replace("\\n", "\n"); } else if (fieldType == typeof(float)) { value = tabFile.GetFloat(row, fieldName); } else if (fieldType == typeof(bool)) { value = tabFile.GetBool(row, fieldName); } else if (fieldType == typeof(double)) { value = tabFile.GetDouble(row, fieldName); } else if (fieldType == typeof(uint)) { value = tabFile.GetUInteger(row, fieldName); } else if (fieldType == typeof(Regex)) { var str = tabFile.GetString(row, fieldName); value = string.IsNullOrEmpty(str) ? null : new Regex(str); } else if (fieldType == typeof(List <string>)) { string sz = tabFile.GetString(row, fieldName); value = KTool.Split <string>(sz, '|'); } else if (fieldType == typeof(List <int>)) { //List<int> retInt = new List<int>(); string szArr = tabFile.GetString(row, fieldName); value = KTool.Split <int>(szArr, '|'); //if (!string.IsNullOrEmpty(szArr)) //{ // string[] szIntArr = szArr.Split('|'); // foreach (string szInt in szIntArr) // { // float parseFloat; // float.TryParse(szInt, out parseFloat); // int parseInt_ = (int)parseFloat; // retInt.Add(parseInt_); // } //} //else // value = new List<int>(); } else if (fieldType == typeof(List <List <string> >)) { string sz = tabFile.GetString(row, fieldName); if (!string.IsNullOrEmpty(sz)) { var szOneList = new List <List <string> >(); string[] szArr = sz.Split('|'); foreach (string szOne in szArr) { string[] szOneArr = szOne.Split('-', ':'); szOneList.Add(new List <string>(szOneArr)); } value = szOneList; } else { value = new List <List <string> >(); } } else if (fieldType == typeof(List <List <int> >)) { string sz = tabFile.GetString(row, fieldName); if (!string.IsNullOrEmpty(sz)) { var zsOneIntList = new List <List <int> >(); string[] szArr = sz.Split('|'); foreach (string szOne in szArr) { List <int> retInts = new List <int>(); string[] szOneArr = szOne.Split('-', ':'); foreach (string szOneInt in szOneArr) { float parseFloat; float.TryParse(szOneInt, out parseFloat); int parseInt_ = (int)parseFloat; retInts.Add(parseInt_); } zsOneIntList.Add(retInts); } value = zsOneIntList; } else { value = new List <List <int> >(); } } //else if (fieldType == typeof (JsonObject)) //{ // string sz = tabFile.GetString(row, fieldName); // value = string.IsNullOrEmpty(sz) ? new JsonObject() : KTool.SplitToJson(sz); //} else { Logger.LogWarning("未知类型: {0}", fieldName); value = null; } if (fieldName == "Id") // 如果是Id主键,确保数字成整数! { int fValue; if (int.TryParse((string)value, out fValue)) { try { value = fValue.ToString(); } catch { Logger.LogError("转型错误...{0}", value.ToString()); } } } field.SetValue(newT, value); } }
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> /// 对比两个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; } } } } }
//void CreateUGUI() //{ // var canvasObj = new GameObject("UICanvas"); // UICanvas = canvasObj.AddComponent<Canvas>(); // UICanvas.renderMode = RenderMode.ScreenSpaceOverlay; // //UICanvas.worldCamera = UiCamera.cachedCamera; // canvasObj.AddComponent<GraphicRaycaster>(); // var scaler = canvasObj.AddComponent<CanvasScaler>(); // scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; // 屏幕固定大小 // scaler.referenceResolution = new Vector2(1080, 1920); // var evtSysObj = new GameObject("EventSystem"); // KTool.SetChild(evtSysObj, canvasObj); // evtSysObj.AddComponent<EventSystem>(); //} private void CreateUIRoot() { GameObject uiRootobj = GameObject.Find("NGUIRoot") ?? new GameObject("NGUIRoot"); UiRoot = uiRootobj.GetComponent <UIRoot>() ?? uiRootobj.AddComponent <UIRoot>(); Debuger.Assert(UiRoot); UiRoot.scalingStyle = UIRoot.Scaling.FixedSizeOnMobiles; // 尝试将NGUI转化成跟2dToolkit镜头一致显示 UiRoot.manualHeight = 1080; //GameDef.ScreenPixelY;//(int)(GameDef.ScreenPixelY / (GameDef.ScreenPixelY / 2f / GameDef.DefaultPixelPerMeters)); // fit width! //UiRoot.manualWidth = 1920;//GameDef.ScreenPixelX; // 屏幕中间位置 //UiRoot.transform.localPosition = new Vector3(GameDef.ScreenPixelX / 2f / GameDef.DefaultPixelPerMeters, // GameDef.ScreenPixelY / 2f / GameDef.DefaultPixelPerMeters, -50); //var scale = 1 / GameDef.DefaultPixelPerMeters; //// 覆盖NGUI的Uiroot自动缩放 //UiRoot.transform.localScale = new Vector3(scale, scale, scale); //UiRoot.enabled = false; GameObject panelRootObj = new GameObject("PanelRoot"); KTool.SetChild(panelRootObj.transform, uiRootobj.transform); Transform panelTrans = panelRootObj.transform; PanelRoot = panelRootObj.AddComponent <UIPanel>(); Debuger.Assert(PanelRoot); PanelRoot.generateNormals = true; var uiCamTrans = uiRootobj.transform.Find("UICamera"); GameObject uiCamObj = uiCamTrans != null ? uiCamTrans.gameObject : new GameObject("UICamera"); KTool.SetChild(uiCamObj.transform, UiRoot.transform); UiCamera = uiCamObj.GetComponent <UICamera>() ?? uiCamObj.AddComponent <UICamera>(); UiCamera.cachedCamera.cullingMask = 1 << (int)UnityLayerDef.UI; UiCamera.cachedCamera.clearFlags = CameraClearFlags.Depth; UiCamera.cachedCamera.orthographic = true; UiCamera.cachedCamera.orthographicSize = GameDef.ScreenPixelY / GameDef.DefaultPixelPerMeters / 2f; // 9.6,一屏19.2米,跟GameCamera一致 UiCamera.cachedCamera.nearClipPlane = -500; UiCamera.cachedCamera.farClipPlane = 500; foreach (UIAnchor.Side side in Enum.GetValues(typeof(UIAnchor.Side))) { GameObject anchorObj = new GameObject(side.ToString()); KTool.SetChild(anchorObj.transform, panelTrans); AnchorSide[side.ToString()] = anchorObj.transform; } GameObject nullAnchor = new GameObject("Null"); KTool.SetChild(nullAnchor.transform, panelTrans); AnchorSide["Null"] = nullAnchor.transform; AnchorSide[""] = AnchorSide[UIAnchor.Side.Center.ToString()]; // default NGUITools.SetLayer(uiRootobj, (int)UnityLayerDef.UI); PressWidget = new GameObject("PressWidget").AddComponent <UIWidget>(); NGUITools.SetLayer(PressWidget.gameObject, (int)UnityLayerDef.UI); KTool.SetChild(PressWidget.gameObject, panelRootObj); PressWidget.SetDimensions(2000, 2000); var col = PressWidget.gameObject.AddComponent <BoxCollider>(); col.size = new Vector3(2000, 2000); PressWidget.autoResizeBoxCollider = true; PressWidget.gameObject.SetActive(false); //UICamera.onDragStart = (go) => //{ // if (go != null) // 点击任意NGUI控件,出现阻挡 // PressWidget.gameObject.SetActive(true); //}; //UICamera.onPress = (go, state) => //{ // if (!state) // 点击任意NGUI控件,出现阻挡 // PressWidget.gameObject.SetActive(false); // //if (go != null) // //{ // // if (go.GetComponent<UIButton>() == null) // // { // // if (go.GetComponent<UIEventListener>() != null && go.GetComponent<UISprite>() != null) // // { // // if (Debug.isDebugBuild) // // { // // Debug.LogWarning("自动加UIButton和ButtonScale - " + go.name, go); // // } // // // 当不包含ButtonScale动画 // // // 并且拥有EventListener和UISprite! // // // 统一加上ButtonScale! // // var bScale = go.GetComponent<UIButtonScale>() ?? go.AddComponent<UIButtonScale>(); // // bScale.pressed = bScale.hover; // // bScale.hover = Vector3.one; // // var bColor = go.GetComponent<UIButton>() ?? go.AddComponent<UIButton>(); // // bColor.hover = Color.white; // // bColor.pressed = Color.white*.8f; // 小小灰 // // } // // } // //} //}; }
/// <summary> /// 清除一个GameObject下面所有的孩子 /// </summary> /// <param name="go"></param> public void DestroyGameObjectChildren(GameObject go) { KTool.DestroyGameObjectChildren(go); }
public static void CreateNewUI() { #if UNITY_5_3_OR_NEWER var currentScene = EditorSceneManager.GetActiveScene().path; #else var currentScene = EditorApplication.currentScene; #endif GameObject mainCamera = GameObject.Find("Main Camera"); if (mainCamera != null) { GameObject.DestroyImmediate(mainCamera); } var uiName = Path.GetFileNameWithoutExtension(currentScene); if (String.IsNullOrEmpty(uiName) || GameObject.Find(uiName) != null) // default use scene name, if exist create random name { uiName = "NewUI_" + Path.GetRandomFileName(); } GameObject uiObj = new GameObject(uiName); uiObj.layer = (int)UnityLayerDef.UI; uiObj.AddComponent <UIWindowAsset>(); var uiPanel = new GameObject("Image").AddComponent <Image>(); uiPanel.transform.parent = uiObj.transform; KTool.ResetLocalTransform(uiPanel.transform); var canvas = uiObj.AddComponent <Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; CanvasScaler canvasScaler = uiObj.AddComponent <CanvasScaler>(); uiObj.AddComponent <GraphicRaycaster>(); //NOTE canvas的分辨率读取AppEngine的设置 var uiSize = new Vector2(1280, 720); var uiResolution = AppEngine.GetConfig("KEngine.UI", "UIResolution"); if (!string.IsNullOrEmpty(uiResolution)) { var sizeArr = uiResolution.Split(','); if (sizeArr.Length >= 2) { uiSize = new Vector2(sizeArr[0].ToInt32(), sizeArr[1].ToInt32()); } } canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; canvasScaler.referenceResolution = uiSize; canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.Expand; if (GameObject.Find("EventSystem") == null) { var evtSystemObj = new GameObject("EventSystem"); evtSystemObj.AddComponent <EventSystem>(); evtSystemObj.AddComponent <StandaloneInputModule>(); #if !UNITY_5_3_OR_NEWER evtSystemObj.AddComponent <TouchInputModule>(); #endif } if (GameObject.Find("Camera") == null) { GameObject cameraObj = new GameObject("Camera"); cameraObj.layer = (int)UnityLayerDef.UI; Camera camera = cameraObj.AddComponent <Camera>(); camera.clearFlags = CameraClearFlags.Skybox; camera.depth = 0; camera.backgroundColor = Color.grey; camera.cullingMask = 1 << (int)UnityLayerDef.UI; camera.orthographicSize = 1f; camera.orthographic = true; camera.nearClipPlane = -2f; camera.farClipPlane = 2f; camera.gameObject.AddComponent <AudioListener>(); } Selection.activeGameObject = uiObj; }
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(); }