123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- using UnityEngine;
- using System.Collections.Generic;
- namespace Fort23.Core
- {
- public enum LayoutType
- {
- Horizontal,
- Vertical
- }
- public class SimpleLayout
- {
- /// <summary>
- /// 根据传入的布局类型,排列 GameObject 列表,水平排列并居中
- /// </summary>
- /// <param name="list">需要排列的 GameObject 列表</param>
- /// <param name="type">布局类型,支持 Horizontal 或 Vertical</param>
- /// <param name="spacing">元素之间的间距</param>
- public static void Layout(List<object> list, LayoutType type, float spacing = 0f)
- {
- // 获取父节点的 RectTransform
- if (list.Count == 0)
- return;
- if (type == LayoutType.Horizontal)
- {
- List<GameObject> activeElements = new List<GameObject>();
- // 筛选 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<RectTransform>();
- totalWidth += rt.rect.width + (i < count - 1 ? spacing : 0);
- }
- // 起始位置的计算:最左侧元素的中心点相对于父节点
- float startX = -totalWidth / 2 + activeElements[0].GetComponent<RectTransform>().rect.width / 2;
- // 设置每个元素的位置
- for (int i = 0; i < count; i++)
- {
- RectTransform rt = activeElements[i].GetComponent<RectTransform>();
- // 更新位置
- rt.anchoredPosition = new Vector2(startX, 0);
- // 移动到下一个元素位置
- startX += rt.rect.width + spacing;
- }
- }
- else if (type == LayoutType.Vertical)
- {
- List<GameObject> activeElements = new List<GameObject>();
- // 筛选 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<RectTransform>();
- totalHeight += rt.rect.height + (i < count - 1 ? spacing : 0);
- }
- // 起始位置的计算:最顶部元素的中心点相对于父节点
- float startY = totalHeight / 2 - activeElements[0].GetComponent<RectTransform>().rect.height / 2;
- // 设置每个元素的位置
- for (int i = 0; i < count; i++)
- {
- RectTransform rt = activeElements[i].GetComponent<RectTransform>();
- // 更新位置
- rt.anchoredPosition = new Vector2(0, startY);
- // 移动到下一个元素位置
- startY -= rt.rect.height + spacing;
- }
- }
- }
- }
- }
|