using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class ThreeDGridLayoutEditor : EditorWindow
{
[MenuItem("Tools/3DLayoutWindow")]
static void OpenThreeDWindow()
{
ThreeDGridLayoutEditor ew = GetWindow<ThreeDGridLayoutEditor>();
}
Transform root;
Vector2 space;
string[] axisOptions = new string[2] { "Horizontal", "Vertital" };
int axis = 0;
int axisCount = 1;
private void OnGUI()
{
EditorGUILayout.Space(10);
root = EditorGUILayout.ObjectField("请选择Group根节点", root, typeof(Transform), true) as Transform;
EditorGUILayout.Space(10);
space = EditorGUILayout.Vector2Field("请输入元素间距", space);
if (space.x < 0)
space.x = 0;
if (space.y < 0)
space.y = 0;
EditorGUILayout.Space(10);
axis = EditorGUILayout.Popup("请选择基准轴", axis, axisOptions);
EditorGUILayout.Space(10);
axisCount = EditorGUILayout.IntField("请输入基准方向元素数量", axisCount);
if (axisCount < 1)
axisCount = 1;
EditorGUILayout.Space(10);
if (GUILayout.Button("重新排列元素"))
RankElements();
}
void RankElements()
{
if (root == null)
{
Debug.LogError("root is null");
return;
}
List<Transform> list = new List<Transform>();
int eCount = root.childCount;
for (int i = 0; i < eCount; i++)
{
if (root.GetChild(i).gameObject.activeSelf)
list.Add(root.GetChild(i));
}
if (space.x == 0 && space.y == 0)
{
Debug.LogError("space is 0,0");
return;
}
Vector3 startPos = new Vector3(0, 0, 0);
CalculateStartPos(list.Count, ref startPos);
RankTransforms(list, space, axis == 0, axisCount, startPos);
}
void CalculateStartPos(int eCount, ref Vector3 startPos)
{
if (axis == 0)
{
int xCount = axisCount;
if (eCount <= xCount)
{
startPos.x = eCount % 2 > 0 ? -(eCount / 2) * space.x : -(eCount / 2 - 0.5f) * space.x;
}
else
{
int zCount = eCount / xCount + (eCount % xCount > 0 ? 1 : 0);
startPos.x = xCount % 2 > 0 ? -(xCount / 2) * space.x : -(xCount / 2 - 0.5f) * space.x;
startPos.z = zCount % 2 > 0 ? (zCount / 2) * space.y : (zCount / 2 - 0.5f) * space.y;
}
}
else
{
int zCount = axisCount;
if (eCount <= zCount)
{
startPos.z = eCount % 2 > 0 ? -(eCount / 2) * space.y : -(eCount / 2 - 0.5f) * space.y;
}
else
{
int xCount = eCount / zCount + (eCount % zCount > 0 ? 1 : 0);
startPos.x = xCount % 2 > 0 ? -(xCount / 2) * space.x : -(xCount / 2 - 0.5f) * space.x;
startPos.z = zCount % 2 > 0 ? (zCount / 2) * space.y : (zCount / 2 - 0.5f) * space.y;
}
}
}
void RankTransforms(List<Transform> rankList, Vector3 spacing, bool isHorizontal, int fixedCount, Vector3 startPos)
{
if (isHorizontal)
{
for (int i = 0; i < rankList.Count; i++)
{
rankList[i].localPosition = startPos + Vector3.right* spacing.x * (i % fixedCount) - Vector3.forward * spacing.y * (i / fixedCount);
}
}
else
{
for (int i = 0; i < rankList.Count; i++)
{
rankList[i].localPosition = startPos - Vector3.forward * spacing.y * (i % fixedCount) + Vector3.right * spacing.x * (i / fixedCount);
}
}
}
}