void GeneratePreview(Item item, UISnapshotPoint point) { if (item == null || item.prefab == null) { return; } { string preview_path = Application.dataPath + "/" + Configure.ResPath + "Preview/" + item.prefab.name + ".png"; if (File.Exists(preview_path)) { Texture texture = UIEditorHelper.LoadTextureInLocal(preview_path); item.tex = texture; } else { Texture Tex = UIEditorHelper.GetAssetPreview(item.prefab); if (Tex != null) { DestroyTexture(item); item.tex = Tex; UIEditorHelper.SaveTextureToPNG(Tex, preview_path); } } item.dynamicTex = false; return; } }
static void OnSelectChange() { LastSelectObj = CurSelectObj; CurSelectObj = Selection.activeObject; //如果要遍历目录,修改为SelectionMode.DeepAssets UnityEngine.Object[] arr = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.TopLevel); if (arr != null && arr.Length > 0) { GameObject selectObj = LastSelectObj as GameObject; if (selectObj != null && (arr[0] is Sprite || arr[0] is Texture2D)) { string assetPath = AssetDatabase.GetAssetPath(arr[0]); Image image = selectObj.GetComponent <Image>(); bool isImgWidget = false; if (image != null) { isImgWidget = true; UIEditorHelper.SetImageByPath(assetPath, image); } if (isImgWidget) { //赋完图后把焦点还给Image节点 EditorApplication.delayCall = delegate { Selection.activeGameObject = LastSelectObj as GameObject; }; } } } }
PreviewItem AddGUID(string guid, int index) { GameObject go = UIEditorHelper.GUIDToObject <GameObject>(guid); if (go != null) { PreviewItem ent = new PreviewItem(); ent.prefab = go; ent.guid = guid; GeneratePreview(ent, false); if (index < mItems.size) { if (!IsInList(mItems, ent)) { mItems.Insert(index, ent); } } else { if (!IsInList(mItems, ent)) { mItems.Add(ent); } } return(ent); } return(null); }
void GeneratePreview(Item item, bool isReCreate = true) { if (item == null || item.prefab == null) { return; } { string preview_path = Configure.ResAssetsPath + "/Preview/" + item.prefab.name + ".png"; if (!isReCreate && File.Exists(preview_path)) { Texture texture = UIEditorHelper.LoadTextureInLocal(preview_path); item.tex = texture; } else { Texture Tex = UIEditorHelper.GetAssetPreview(item.prefab); if (Tex != null) { DestroyTexture(item); item.tex = Tex; UIEditorHelper.SaveTextureToPNG(Tex, preview_path); } } item.dynamicTex = false; return; } }
public static GameObject CreatNewLayout(bool isNeedLayout = true) { GameObject testUI = UIEditorHelper.GetUITestRootNode(); string file_path = Path.Combine(Configure.ResAssetsPath, "Canvas.prefab"); file_path = FileUtil.GetProjectRelativePath(file_path); GameObject layout_prefab = UnityEditor.AssetDatabase.LoadAssetAtPath(file_path, typeof(UnityEngine.Object)) as GameObject; GameObject layout = GameObject.Instantiate(layout_prefab) as GameObject; layout.transform.SetParent(testUI.transform); Vector3 last_pos = layout.transform.localPosition; layout.transform.localPosition = new Vector3(last_pos.x, last_pos.y, 0); if (!isNeedLayout) { Transform child = layout.transform.Find("Layout"); // layout.transform.DetachChildren(); if (child != null) { Undo.DestroyObjectImmediate(child.gameObject); } } Selection.activeGameObject = layout; RectTransform trans = layout.transform as RectTransform; SceneView.lastActiveSceneView.MoveToView(trans); return(layout); }
//[MenuItem("UIEditor/另存为 ")] public static void SaveAnotherLayoutMenu() { if (Selection.activeGameObject == null) { EditorUtility.DisplayDialog("Warning", "I don't know which prefab you want to save", "Ok"); return; } LayoutInfo layout = Selection.activeGameObject.GetComponentInParent <LayoutInfo>(); if (layout != null) { GameObject editingView = layout.EditingView; if (editingView != null) { UIEditorHelper.SaveAnotherLayout(layout.GetComponent <Canvas>(), editingView.transform); } } // for (int i = 0; i < layout.transform.childCount; i++) // { // Transform child = layout.transform.GetChild(i); // if (child.GetComponent<Decorate>() != null) // continue; // GameObject child_obj = child.gameObject; // //Debug.Log("child type :" + PrefabUtility.GetPrefabType(child_obj)); // //判断选择的物体,是否为预设 // PrefabType cur_prefab_type = PrefabUtility.GetPrefabType(child_obj); // UIEditorHelper.SaveAnotherLayout(layout, child); // break; // } }
static public Transform GetContainerUnderMouse(Vector3 mouse_abs_pos, GameObject ignore_obj = null) { GameObject testUI = UIEditorHelper.GetUITestRootNode(); List <RectTransform> list = new List <RectTransform>(); Canvas[] containers = Transform.FindObjectsOfType <Canvas>(); Vector3[] corners = new Vector3[4]; foreach (var item in containers) { if (ignore_obj == item.gameObject || item.transform.parent != testUI.transform) { continue; } RectTransform trans = item.transform as RectTransform; if (trans != null) { //获取节点的四个角的世界坐标,分别按顺序为左下左上,右上右下 trans.GetWorldCorners(corners); if (mouse_abs_pos.x >= corners[0].x && mouse_abs_pos.y <= corners[1].y && mouse_abs_pos.x <= corners[2].x && mouse_abs_pos.y >= corners[3].y) { list.Add(trans); } } } if (list.Count <= 0) { return(null); } list.Sort((RectTransform a, RectTransform b) => { return((a.GetSiblingIndex() == b.GetSiblingIndex()) ? 0 : ((a.GetSiblingIndex() < b.GetSiblingIndex()) ? 1 : -1)); } ); return(GetRootLayout(list[0])); }
static bool HandleDragAsset(SceneView sceneView, Object handleObj) { Event e = Event.current; Camera cam = sceneView.camera; Vector3 mouse_abs_pos = e.mousePosition; mouse_abs_pos.y = cam.pixelHeight - mouse_abs_pos.y; mouse_abs_pos = sceneView.camera.ScreenToWorldPoint(mouse_abs_pos); if (handleObj.GetType() == typeof(Sprite) || handleObj.GetType() == typeof(Texture2D)) { GameObject box = new GameObject("Image_1", typeof(Image)); box.transform.position = mouse_abs_pos; Transform container_trans = UIEditorHelper.GetContainerUnderMouse(mouse_abs_pos, box); if (container_trans == null) { //没有容器的话就创建一个 container_trans = NewLayoutAndEventSys(mouse_abs_pos); } box.transform.SetParent(container_trans); mouse_abs_pos.z = container_trans.position.z; box.transform.position = mouse_abs_pos; Selection.activeGameObject = box; //生成唯一的节点名字 box.name = CommonHelper.GenerateUniqueName(container_trans.gameObject, handleObj.name); //赋上图片 Image imageBoxCom = box.GetComponent <Image>(); if (imageBoxCom != null) { imageBoxCom.raycastTarget = false; string assetPath = AssetDatabase.GetAssetPath(handleObj); UIEditorHelper.SetImageByPath(assetPath, imageBoxCom); return(true); } } else { GameObject new_obj = GameObject.Instantiate(handleObj) as GameObject; if (new_obj != null) { new_obj.transform.position = mouse_abs_pos; GameObject ignore_obj = new_obj; Transform container_trans = UIEditorHelper.GetContainerUnderMouse(mouse_abs_pos, ignore_obj); if (container_trans == null) { container_trans = NewLayoutAndEventSys(mouse_abs_pos); } new_obj.transform.SetParent(container_trans); mouse_abs_pos.z = container_trans.position.z; new_obj.transform.position = mouse_abs_pos; Selection.activeGameObject = new_obj; //生成唯一的节点名字 new_obj.name = CommonHelper.GenerateUniqueName(container_trans.gameObject, handleObj.name); return(true); } } return(false); }
private static Transform NewLayoutAndEventSys(Vector3 pos) { GameObject layout = UIEditorHelper.CreatNewLayout(); pos.z = 0; layout.transform.position = pos; return(UIEditorHelper.GetRootLayout(layout.transform)); }
//[MenuItem("UIEditor/保存 " + Configure.ShortCut.SaveUIPrefab, false, 2)] public static void SaveLayout(GameObject o, bool isQuiet) { GameObject saveObj = o == null ? Selection.activeGameObject : (o as GameObject); if (saveObj == null) { EditorUtility.DisplayDialog("Warning", "I don't know which prefab you want to save", "Ok"); return; } Canvas layout = saveObj.GetComponentInParent <Canvas>(); if (layout == null) { EditorUtility.DisplayDialog("Warning", "select any layout below UITestNode/canvas to save", "Ok"); return; } Transform real_layout = GetRealLayout(saveObj); if (real_layout != null) { GameObject child_obj = real_layout.gameObject; //判断选择的物体,是否为预设 PrefabType cur_prefab_type = PrefabUtility.GetPrefabType(child_obj); if (PrefabUtility.GetPrefabType(child_obj) == PrefabType.PrefabInstance || cur_prefab_type == PrefabType.DisconnectedPrefabInstance) { UnityEngine.Object parentObject = PrefabUtility.GetPrefabParent(child_obj); //替换预设,Note:只能用ConnectToPrefab,不然会重复加多几个同名控件的 PrefabUtility.ReplacePrefab(child_obj, parentObject, ReplacePrefabOptions.ConnectToPrefab); //刷新 AssetDatabase.Refresh(); if (Configure.IsShowDialogWhenSaveLayout && !isQuiet) { EditorUtility.DisplayDialog("Tip", "Save Succeed!", "Ok"); } //保存时先记录一下,如果是运行游戏时保存了,结束游戏时就要重新加载界面了,不然会重置回运行游戏前的 ReloadLayoutOnExitGame reloadCom = layout.GetComponent <ReloadLayoutOnExitGame>(); if (reloadCom) { reloadCom.SetHadSaveOnRunTime(true); } Debug.Log("Save Succeed!"); LayoutInfo layoutInfo = layout.GetComponent <LayoutInfo>(); if (layoutInfo != null) { layoutInfo.SaveToConfigFile(); } } else { UIEditorHelper.SaveAnotherLayout(layout, real_layout); } } else { Debug.Log("save failed!are you select any widget below canvas?"); } }
//初始化 void Load() { m_tab = EditorPrefs.GetInt("PrefabWin Prefab Tab", 0); SizePercent = EditorPrefs.GetFloat("PrefabWin_SizePercent", 0.5f); foreach (PreviewItem item in mItems) { DestroyTexture(item); } mItems.Clear(); //读取本地存储的数据 string data = EditorPrefs.GetString(saveKey, ""); if (string.IsNullOrEmpty(data)) { Resets(); } else { if (string.IsNullOrEmpty(data)) { return; } string[] guids = data.Split('|'); foreach (string s in guids) { AddGUID(s, -1); } RectivateLights(); } //加载默认文件夹里面的资源 if (m_tab == 0 && Configure.PrefabWinBasicComPath != "") { List <string> filtered = UIEditorHelper.GetAllPrefabs(Configure.PrefabWinBasicComPath); for (int i = 0; i < filtered.Count; i++) { AddGUID(AssetDatabase.AssetPathToGUID(filtered[i]), -1); } RectivateLights(); } if (m_tab == 1 && Configure.PrefabWinCommonPanelPath != "") { List <string> filtered = UIEditorHelper.GetAllPrefabs(Configure.PrefabWinCommonPanelPath); for (int i = 0; i < filtered.Count; i++) { AddGUID(AssetDatabase.AssetPathToGUID(filtered[i]), -1); } RectivateLights(); } loadTextData(Configure.ColorDataPath, ref colocDic); loadTextData(Configure.UIWidgetPath, ref uiWidgetDic); loadTextData(Configure.UIInfoPath, ref uiInfoDic); loadTextData(Configure.UIStatePath, ref uiStateDic); }
public override void OnInspectorGUI() { Decorate widget = target as Decorate; if (GUILayout.Button("加载外部图片", GUILayout.Height(30))) { UIEditorHelper.SelectPicForDecorate(widget); } }
static public void AddCommonItems(GameObject[] targets) { if (targets == null || targets.Length <= 0) { AddItem("新建", false, UIEditorHelper.CreatNewLayoutForMenu, null); AddItem("打开界面", false, UIEditorHelper.LoadLayout, null); } if (targets != null && targets.Length > 0) { AddItem("保存", false, UIEditorHelper.SaveLayoutForMenu, null); AddItem("另存为", false, UIEditorHelper.SaveAnotherLayoutContextMenu, null); AddItem("重新加载", false, UIEditorHelper.ReLoadLayoutForMenu, null); AddSeparator("///"); AddItem("复制选中控件名", false, UIEditorHelper.CopySelectWidgetName, null); //如果选中超过1个节点的话 if (targets.Length > 1) { AddAlignMenu(); AddItem("同流合污", false, UILayoutTool.MakeGroup, null); } AddSeparator("///"); if (targets.Length == 1) { AddUIMenu(); AddUIComponentMenu(); AddPriorityMenu(); if (UIEditorHelper.IsNodeCanDivide(targets[0])) { AddItem("分道扬镖", false, UILayoutTool.UnGroup, null); } Decorate uiBase = targets[0].GetComponent <Decorate>(); if (uiBase != null) { if (uiBase.gameObject.hideFlags == HideFlags.NotEditable) { AddItem("解锁", false, UIEditorHelper.UnLockWidget, null); } else { AddItem("锁定", false, UIEditorHelper.LockWidget, null); } } } AddShowOrHideMenu(); AddSeparator("///"); AddItem("添加参考图", false, UIEditorHelper.CreateDecorate, null); } AddItem("排序所有界面", false, UILayoutTool.ResortAllLayout, null); AddItem("清空界面", false, UIEditorHelper.ClearAllCanvas, null); }
public void LoadSpr(string path) { InitComponent(); if (spr_path != path) { spr_path = path; _image.sprite = UIEditorHelper.LoadSpriteInLocal(path); _image.SetNativeSize(); gameObject.name = CommonHelper.GetFileNameByPath(path); } }
public void LoadSpr(string path) { InitComponent(); //Debug.Log("path : " + path); if (spr_path != path) { spr_path = path; _image.sprite = UIEditorHelper.LoadSpriteInLocal(path); _image.SetNativeSize(); gameObject.name = CommonHelper.GetFileNameByPath(path); //Debug.Log("_image.sprite :" + (_image.sprite != null).ToString()); } }
private static GameObject GetLoadedLayout(string layoutPath) { GameObject testUI = UIEditorHelper.GetUITestRootNode(); if (testUI != null) { LayoutInfo[] layoutInfos = testUI.GetComponentsInChildren <LayoutInfo>(true); foreach (var item in layoutInfos) { if (item.LayoutPath == layoutPath) { return(item.gameObject); } } } return(null); }
void AddItem(GameObject go, int index) { string guid = UIEditorHelper.ObjectToGUID(go); if (string.IsNullOrEmpty(guid)) { string path = EditorUtility.SaveFilePanelInProject("Save a prefab", go.name + ".prefab", "prefab", "Save prefab as...", ""); if (string.IsNullOrEmpty(path)) { return; } go = PrefabUtility.CreatePrefab(path, go); if (go == null) { return; } guid = UIEditorHelper.ObjectToGUID(go); if (string.IsNullOrEmpty(guid)) { return; } } PreviewItem ent = new PreviewItem(); ent.prefab = go; ent.guid = guid; GeneratePreview(ent); RectivateLights(); if (index < mItems.size) { mItems.Insert(index, ent); } else { mItems.Add(ent); } Save(); }
public static void CreateDecorate() { if (Selection.activeTransform != null) { Canvas canvas = Selection.activeTransform.GetComponentInParent <Canvas>(); if (canvas != null) { Decorate decor = CreateEmptyDecorate(canvas.transform); Selection.activeTransform = decor.transform; if (Configure.OpenSelectPicDialogWhenAddDecorate) { bool isSucceed = UIEditorHelper.SelectPicForDecorate(decor); if (!isSucceed) { GameObject.DestroyImmediate(decor.gameObject); } } } } }
void SaveTextureToPng() { for (int i = 0; i < mItems.size; i++) { Item item = mItems[i]; if (item == null || item.prefab == null || item.tex == null || item.isDirty == false) { continue; } UIEditorHelper.SaveTextureToPNG(item.tex, GetPreviewPath(item)); string preview_path = GetPreviewPath(item); item.tex = UIEditorHelper.LoadTextureInLocal(preview_path); item.isDirty = false; } GameObject root = GameObject.Find(Configure.PreviewCanvasName); if (root) { DestroyImmediate(root); } }
public static GameObject CreatNewLayout(bool isNeedLayout = true) { GameObject testUI = UIEditorHelper.GetUITestRootNode(); const string file_path = Configure.ResAssetsPath + "Canvas.prefab"; GameObject layout_prefab = UnityEditor.AssetDatabase.LoadAssetAtPath(file_path, typeof(UnityEngine.Object)) as GameObject; GameObject layout = GameObject.Instantiate(layout_prefab) as GameObject; layout.transform.SetParent(testUI.transform); if (!isNeedLayout) { Transform child = layout.transform.GetChild(0); layout.transform.DetachChildren(); Undo.DestroyObjectImmediate(child.gameObject); } Selection.activeGameObject = layout; RectTransform trans = layout.transform as RectTransform; SceneView.lastActiveSceneView.MoveToView(trans); return(layout); }
public static void SaveLayout(object o = null) { if (Selection.activeGameObject == null) { EditorUtility.DisplayDialog("Warning", "I don't know which prefab you want to save", "Ok"); return; } Canvas layout = Selection.activeGameObject.GetComponentInParent <Canvas>(); for (int i = 0; i < layout.transform.childCount; i++) { Transform child = layout.transform.GetChild(i); if (child.GetComponent <Decorate>() != null) { continue; } GameObject child_obj = child.gameObject; //Debug.Log("child type :" + PrefabUtility.GetPrefabType(child_obj)); //判断选择的物体,是否为预设 PrefabType cur_prefab_type = PrefabUtility.GetPrefabType(child_obj); if (PrefabUtility.GetPrefabType(child_obj) == PrefabType.PrefabInstance || cur_prefab_type == PrefabType.DisconnectedPrefabInstance) { UnityEngine.Object parentObject = PrefabUtility.GetPrefabParent(child_obj); //替换预设 PrefabUtility.ReplacePrefab(child_obj, parentObject, ReplacePrefabOptions.Default); //刷新 AssetDatabase.Refresh(); if (Configure.IsShowDialogWhenSaveLayout) { EditorUtility.DisplayDialog("Tip", "Save Succeed!", "Ok"); } Debug.Log("Save Succeed!"); } else { UIEditorHelper.SaveAnotherLayout(layout, child); } } }
private void OnApplicationQuit() { Debug.Log("OnApplicationQuit"); isRunningGame = false; if (layout_open_in_playmode.Count > 0 && U3DExtends.Configure.ReloadLayoutOnExitGame) { System.Action <UnityEditor.PlayModeStateChange> p = null; p = new System.Action <UnityEditor.PlayModeStateChange>((UnityEditor.PlayModeStateChange c) => { foreach (var item in layout_open_in_playmode) { // Debug.Log("item.Key : "+item.Key); Transform layout = UIEditorHelper.LoadLayoutByPath(item.Key); if (layout != null) { layout.localPosition = item.Value; } } layout_open_in_playmode.Clear(); UnityEditor.EditorApplication.playModeStateChanged -= p; }); UnityEditor.EditorApplication.playModeStateChanged += p; } }
//[MenuItem("UIEditor/另存为 ")] public static void SaveAnotherLayoutMenu() { if (Selection.activeGameObject == null) { EditorUtility.DisplayDialog("Warning", "I don't know which prefab you want to save", "Ok"); return; } Canvas layout = Selection.activeGameObject.GetComponentInParent <Canvas>(); for (int i = 0; i < layout.transform.childCount; i++) { Transform child = layout.transform.GetChild(i); if (child.GetComponent <Decorate>() != null) { continue; } GameObject child_obj = child.gameObject; //Debug.Log("child type :" + PrefabUtility.GetPrefabType(child_obj)); //判断选择的物体,是否为预设 PrefabType cur_prefab_type = PrefabUtility.GetPrefabType(child_obj); UIEditorHelper.SaveAnotherLayout(layout, child); } }
public static void CreateDecorate(object o) { if (Selection.activeTransform != null) { Canvas canvas = Selection.activeTransform.GetComponentInParent <Canvas>(); if (canvas != null) { const string file_path = Configure.ResAssetsPath + "Decorate.prefab"; GameObject decorate_prefab = UnityEditor.AssetDatabase.LoadAssetAtPath(file_path, typeof(UnityEngine.Object)) as GameObject; GameObject decorate = GameObject.Instantiate(decorate_prefab) as GameObject; decorate.transform.parent = canvas.transform; RectTransform rectTrans = decorate.transform as RectTransform; rectTrans.SetAsFirstSibling(); rectTrans.localPosition = Vector3.zero; Selection.activeTransform = rectTrans; if (Configure.OpenSelectPicDialogWhenAddDecorate) { Decorate decor = rectTrans.GetComponent <Decorate>(); UIEditorHelper.SelectPicForDecorate(decor); } } } }
//打开界面时,从项目临时文件夹找到对应界面的参照图配置,然后生成参照图 public void ApplyConfig(string view_path) { string layout_path_md5 = UIEditorHelper.GenMD5String(view_path); string confighFilePath = ConfigPath + "/" + layout_path_md5 + ".txt"; if (!File.Exists(confighFilePath)) { return; } string content = File.ReadAllText(confighFilePath); int pos_end_index = content.IndexOf(RealPosEndStr); if (pos_end_index == -1) { Debug.Log("cannot find real layout pos config on ApplyConfig : " + view_path); return; } string real_layout_pos_str = content.Substring(RealPosStartStr.Length, pos_end_index - RealPosStartStr.Length); string[] pos_cfg = real_layout_pos_str.Split(' '); if (pos_cfg.Length == 2) { RectTransform real_layout = UIEditorHelper.GetRealLayout(gameObject) as RectTransform;//先拿到真实的界面prefab if (real_layout == null) { Debug.Log("cannot find real layout on ApplyConfig : " + view_path); return; } real_layout.localPosition = new Vector3(float.Parse(pos_cfg[0]), float.Parse(pos_cfg[1]), real_layout.localPosition.z); } else { Debug.Log("cannot find real layout pos xy config on ApplyConfig : " + view_path); return; } content = content.Substring(pos_end_index + RealPosEndStr.Length); if (content == "") { return;//有些界面没参考图也是正常的,直接返回 } string[] decorate_cfgs = content.Split('*'); for (int i = 0; i < decorate_cfgs.Length; i++) { string[] cfgs = decorate_cfgs[i].Split('#'); if (cfgs.Length == 3) { Decorate decor = UIEditorHelper.CreateEmptyDecorate(transform); decor.SprPath = cfgs[0]; RectTransform rectTrans = decor.GetComponent <RectTransform>(); if (rectTrans != null) { //IFormatter formatter = new BinaryFormatter();//使用序列化工具的话就可以保存多点信息,但实现复杂了,暂用简单的吧 string[] pos = cfgs[1].Split(' '); if (pos.Length == 2) { rectTrans.localPosition = new Vector2(float.Parse(pos[0]), float.Parse(pos[1])); } string[] size = cfgs[2].Split(' '); if (size.Length == 2) { rectTrans.sizeDelta = new Vector2(float.Parse(size[0]), float.Parse(size[1])); } } } else { Debug.Log("warning : detect a wrong decorate config file!"); return; } } }
//绘制预览界面 public void DrawPreviewEvent() { Event currentEvent = Event.current; EventType type = currentEvent.type; int x = m_cellPadding, y = m_cellPadding; int width = Screen.width - m_cellPadding; int spacingX = cellSize + m_cellPadding; int spacingY = spacingX; if (m_mode == Mode.DetailedMode) { spacingY += 32; } GameObject[] draggeds = draggedObjects; bool isDragging = (draggeds != null); int indexUnderMouse = GetCellUnderMouse(spacingX, spacingY); if (isDragging) { foreach (var gameObject in draggeds) { var result = FindItem(gameObject); if (result != null) { _selections.Add(result); } } } string searchFilter = EditorPrefs.GetString("PrefabWin_SearchFilter", null); if (mReset && type == EventType.Repaint) { mReset = false; foreach (PreviewItem item in mItems) { GeneratePreview(item, false); } RectivateLights(); } bool eligibleToDrag = (currentEvent.mousePosition.y < Screen.height - 40); if (type == EventType.MouseDown) { m_mouseIsInside = true; } else if (type == EventType.MouseDrag) { m_mouseIsInside = true; if (indexUnderMouse != -1 && eligibleToDrag) { if (draggedObjectIsOurs) { DragAndDrop.StartDrag("Prefab Tool"); } currentEvent.Use(); } } else if (type == EventType.MouseUp) { DragAndDrop.PrepareStartDrag(); m_mouseIsInside = false; Repaint(); } else if (type == EventType.DragUpdated) { m_mouseIsInside = true; UpdateVisual(); currentEvent.Use(); } else if (type == EventType.DragPerform) { if (draggeds != null) { if (_selections != null) { foreach (var selection in _selections) { DestroyTexture(selection); mItems.Remove(selection); } } foreach (var dragged in draggeds) { AddItem(dragged, indexUnderMouse); ++indexUnderMouse; } draggeds = null; } m_mouseIsInside = false; currentEvent.Use(); } else if (type == EventType.DragExited || type == EventType.Ignore) { m_mouseIsInside = false; } if (!m_mouseIsInside) { _selections.Clear(); draggeds = null; } BetterList <int> indices = new BetterList <int>(); for (int i = 0; i < mItems.size;) { if (draggeds != null && indices.size == indexUnderMouse) { indices.Add(-1); } var has = _selections.Exists(item => item == mItems[i]); if (!has) { if (string.IsNullOrEmpty(searchFilter) || mItems[i].prefab.name.IndexOf(searchFilter, System.StringComparison.CurrentCultureIgnoreCase) != -1) { indices.Add(i); } } ++i; } if (!indices.Contains(-1)) { indices.Add(-1); } if (eligibleToDrag && type == EventType.MouseDown && indexUnderMouse > -1) { GUIUtility.keyboardControl = 0; if (currentEvent.button == 0 && indexUnderMouse < indices.size) { int index = indices[indexUnderMouse]; if (index != -1 && index < mItems.size) { _selections.Add(mItems[index]); draggedObjects = _selections.Select(item => item.prefab).ToArray(); draggeds = _selections.Select(item => item.prefab).ToArray(); currentEvent.Use(); } } } m_pos = EditorGUILayout.BeginScrollView(m_pos); { Color normal = new Color(1f, 1f, 1f, 0.5f); for (int i = 0; i < indices.size; ++i) { int index = indices[i]; PreviewItem item = (index != -1) ? mItems[index] : _selections.Count == 0 ? null : _selections[0]; if (item != null && item.prefab == null) { mItems.RemoveAt(index); continue; } Rect rect = new Rect(x, y, cellSize, cellSize); Rect inner = rect; inner.xMin += 2f; inner.xMax -= 2f; inner.yMin += 2f; inner.yMax -= 2f; rect.yMax -= 1f; if (!isDragging && (m_mode == Mode.CompactMode || (item == null || item.tex != null))) { m_content.tooltip = (item != null) ? item.prefab.name : "Click to add"; } else { m_content.tooltip = ""; } GUI.color = normal; UIEditorHelper.DrawTiledTexture(inner, UIEditorHelper.backdropTexture); GUI.color = Color.white; GUI.backgroundColor = normal; if (GUI.Button(rect, m_content, "Button")) { if (item == null || currentEvent.button == 0) { string path = EditorUtility.OpenFilePanel("Add a prefab", "", "prefab"); if (!string.IsNullOrEmpty(path)) { PreviewItem newEnt = CreateItemByPath(path); if (newEnt != null) { mItems.Add(newEnt); Save(); } } } else if (currentEvent.button == 1) { ContextMenu.AddItemWithArge("更新预览", false, delegate { GeneratePreview(item, true); }, index); ContextMenu.AddItemWithArge("删除当前", false, RemoveItem, index); ContextMenu.Show(); } } string caption = (item == null) ? "" : item.prefab.name.Replace("Control - ", ""); if (item != null) { if (item.tex == null) { GeneratePreview(item, false); } if (item.tex != null) { GUI.DrawTexture(inner, item.tex); var labelPos = new Rect(inner); var labelStyle = EditorStyles.label; labelPos.height = labelStyle.lineHeight; labelPos.y = inner.height - labelPos.height + 5; labelStyle.fontSize = 16; labelStyle.alignment = TextAnchor.LowerCenter; { GUI.color = Color.black; var name = item.prefab.name.Split('('); if (name.Length == 2) { GUI.Label(rect, name[0] + "\n(" + name[1], labelStyle); } else { GUI.Label(rect, item.prefab.name, labelStyle); } } labelStyle.alignment = TextAnchor.UpperLeft; labelStyle.fontSize = m_labelDefaultFontSize; } else if (m_mode != Mode.DetailedMode) { GUI.Label(inner, caption, m_style); caption = ""; } } else { GUI.Label(inner, "Add", m_style); } if (m_mode == Mode.DetailedMode) { GUI.backgroundColor = new Color(1f, 1f, 1f, 0.5f); GUI.contentColor = new Color(1f, 1f, 1f, 0.7f); GUI.Label(new Rect(rect.x, rect.y + rect.height, rect.width, 32f), caption, "ProgressBarBack"); GUI.contentColor = Color.white; GUI.backgroundColor = Color.white; } x += spacingX; if (x + spacingX > width) { y += spacingY; x = m_cellPadding; } } GUILayout.Space(y + spacingY); } EditorGUILayout.EndScrollView(); GUILayout.BeginHorizontal(); { string after = EditorGUILayout.TextField("", searchFilter, "SearchTextField", GUILayout.Width(Screen.width - 20f)); if (GUILayout.Button("", "SearchCancelButton", GUILayout.Width(18f))) { after = ""; GUIUtility.keyboardControl = 0; } if (searchFilter != after) { EditorPrefs.SetString("PrefabWin_SearchFilter", after); searchFilter = after; } } GUILayout.EndHorizontal(); SizePercent = EditorGUILayout.Slider(SizePercent, 0, 2); }
//本来坐标或大小变更时也需要再保存一下,但是需要监听pos size等变更又要io保存,怕太多参照图时影响性能,所以还是界面保存时再一起保存吧 public bool SaveToConfigFile() { string select_path = FileUtil.GetProjectRelativePath(LayoutPath); string layout_path_md5 = UIEditorHelper.GenMD5String(select_path); RectTransform real_layout = UIEditorHelper.GetRealLayout(gameObject) as RectTransform;//先拿到真实的界面prefab if (select_path == "" || real_layout == null) { //界面还未保存,等保存时再调用本函数 return(false); } RectTransform curTrans = transform as RectTransform; bool hadDecorateTransChanged = false; bool hadTransChanged = true; if (real_layout.localPosition == _lastRealLayoutPos && real_layout.sizeDelta == _lastRealLayoutSize) { hadTransChanged = false; } _lastRealLayoutPos = real_layout.localPosition; _lastRealLayoutSize = real_layout.sizeDelta; if (!Directory.Exists(ConfigPath)) { Directory.CreateDirectory(ConfigPath); } string savePath = ConfigPath + "/" + layout_path_md5 + ".txt"; StringBuilder content = new StringBuilder(); content.Append(RealPosStartStr); content.Append(real_layout.localPosition.x.ToString()); content.Append(' '); content.Append(real_layout.localPosition.y.ToString()); content.Append(RealPosEndStr); Decorate[] decorates = transform.GetComponentsInChildren <Decorate>(); for (int i = 0; i < decorates.Length; i++) { RectTransform rectTrans = decorates[i].GetComponent <RectTransform>(); if (rectTrans != null) { content.Append(decorates[i].SprPath); content.Append('#'); content.Append(rectTrans.localPosition.x.ToString()); content.Append(' '); content.Append(rectTrans.localPosition.y.ToString()); content.Append('#'); content.Append(rectTrans.sizeDelta.x.ToString()); content.Append(' '); content.Append(rectTrans.sizeDelta.y.ToString()); content.Append('*');//分隔不同的参照图 if (decorates[i].IsChangedTrans()) { decorates[i].SaveTrans(); hadDecorateTransChanged = true; } } } if (hadTransChanged || hadDecorateTransChanged) { if (content[content.Length - 1] == '*') { content.Remove(content.Length - 1, 1);//删掉最后一个分隔符 } File.WriteAllText(savePath, content.ToString()); return(true); } //当真实界面的坐标和参照图的变换没变的话就不需要保存了 return(false); }
//[MenuItem("UIEditor/Operate/组合")] public static void MakeGroup(object o) { if (Selection.gameObjects == null || Selection.gameObjects.Length <= 0) { EditorUtility.DisplayDialog("Error", "当前没有选中节点", "Ok"); return; } //先判断选中的节点是不是挂在同个父节点上的 Transform parent = Selection.gameObjects[0].transform.parent; foreach (var item in Selection.gameObjects) { Debug.Log("item name :" + item.name); if (item.transform.parent != parent) { EditorUtility.DisplayDialog("Error", "不能跨容器组合", "Ok"); return; } } GameObject box = new GameObject("container", typeof(RectTransform)); RectTransform rectTrans = box.GetComponent <RectTransform>(); if (rectTrans != null) { Vector2 left_top_pos = new Vector2(99999, -99999); Vector2 right_bottom_pos = new Vector2(-99999, 99999); foreach (var item in Selection.gameObjects) { Bounds bound = UIEditorHelper.GetBounds(item); Vector3 boundMin = item.transform.parent.InverseTransformPoint(bound.min); Vector3 boundMax = item.transform.parent.InverseTransformPoint(bound.max); Debug.Log("bound : " + boundMin.ToString() + " max:" + boundMax.ToString()); if (boundMin.x < left_top_pos.x) { left_top_pos.x = boundMin.x; } if (boundMax.y > left_top_pos.y) { left_top_pos.y = boundMax.y; } if (boundMax.x > right_bottom_pos.x) { right_bottom_pos.x = boundMax.x; } if (boundMin.y < right_bottom_pos.y) { right_bottom_pos.y = boundMin.y; } } rectTrans.SetParent(parent); rectTrans.sizeDelta = new Vector2(right_bottom_pos.x - left_top_pos.x, left_top_pos.y - right_bottom_pos.y); left_top_pos.x += rectTrans.sizeDelta.x / 2; left_top_pos.y -= rectTrans.sizeDelta.y / 2; rectTrans.localPosition = left_top_pos; //需要先生成好Box和设置好它的坐标和大小才可以把选中的节点挂进来,注意要先排好序,不然层次就乱了 GameObject[] sorted_objs = Selection.gameObjects.OrderBy(x => x.transform.GetSiblingIndex()).ToArray(); for (int i = 0; i < sorted_objs.Length; i++) { sorted_objs[i].transform.SetParent(rectTrans, true); } } Selection.activeGameObject = box; }