//[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; }