using UnityEngine; using System.Collections.Generic; namespace Fort23.Core { public enum LayoutType { Horizontal, Vertical } public class SimpleLayout { /// /// 根据传入的布局类型,排列 GameObject 列表,水平排列并居中 /// /// 需要排列的 GameObject 列表 /// 布局类型,支持 Horizontal 或 Vertical /// 元素之间的间距 public static void Layout(List list, LayoutType type, float spacing = 0f) { // 获取父节点的 RectTransform if (list.Count == 0) return; if (type == LayoutType.Horizontal) { List activeElements = new List(); // 筛选 active 为 true 的元素 foreach (object item in list) { GameObject g = item as GameObject; if (g != null && g.activeSelf) { activeElements.Add(g); } } int count = activeElements.Count; // 如果没有 active 的元素,直接返回 if (count == 0) return; // 计算起始位置,使中心点的元素对齐父节点中心 float totalWidth = 0f; for (int i = 0; i < count; i++) { RectTransform rt = activeElements[i].GetComponent(); totalWidth += rt.rect.width + (i < count - 1 ? spacing : 0); } // 起始位置的计算:最左侧元素的中心点相对于父节点 float startX = -totalWidth / 2 + activeElements[0].GetComponent().rect.width / 2; // 设置每个元素的位置 for (int i = 0; i < count; i++) { RectTransform rt = activeElements[i].GetComponent(); // 更新位置 rt.anchoredPosition = new Vector2(startX, 0); // 移动到下一个元素位置 startX += rt.rect.width + spacing; } } else if (type == LayoutType.Vertical) { List activeElements = new List(); // 筛选 active 为 true 的元素 foreach (object item in list) { GameObject g = item as GameObject; if (g != null && g.activeSelf) { activeElements.Add(g); } } int count = activeElements.Count; // 如果没有 active 的元素,直接返回 if (count == 0) return; // 计算起始位置,使中心点的元素对齐父节点中心 float totalHeight = 0f; for (int i = 0; i < count; i++) { RectTransform rt = activeElements[i].GetComponent(); totalHeight += rt.rect.height + (i < count - 1 ? spacing : 0); } // 起始位置的计算:最顶部元素的中心点相对于父节点 float startY = totalHeight / 2 - activeElements[0].GetComponent().rect.height / 2; // 设置每个元素的位置 for (int i = 0; i < count; i++) { RectTransform rt = activeElements[i].GetComponent(); // 更新位置 rt.anchoredPosition = new Vector2(0, startY); // 移动到下一个元素位置 startY -= rt.rect.height + spacing; } } } } }