UGUI—布局组(LayoutGroup)

作者:追风剑情 发布于:2021-12-8 10:50 分类:Unity3d

一、水平居中布局

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 水平居中布局
/// </summary>
public class UIHorizontalLayoutGroup : MonoBehaviour
{
    //间隙
    public float spacing = 20f;
    //Group宽度
    public float groupWidth { get; private set; }

    [System.NonSerialized] 
    private RectTransform m_Rect;
    protected RectTransform rectTransform
    {
        get
        {
            if (m_Rect == null)
                m_Rect = GetComponent<RectTransform>();
            return m_Rect;
        }
    }

    [System.NonSerialized] 
    private List<RectTransform> m_RectChildren = new List<RectTransform>();

    private void CalculateLayoutInputHorizontal()
    {
        m_RectChildren.Clear();
        groupWidth = 0;
        int childCount = rectTransform.childCount;
        for (int i = 0; i < childCount; i++)
        {
            var rect = rectTransform.GetChild(i) as RectTransform;
            if (rect == null || !rect.gameObject.activeInHierarchy)
                continue;
            m_RectChildren.Add(rect);
            if (i > 0)
                groupWidth += spacing;
            groupWidth += rect.rect.width;
        }
    }

    public void UpdateLayout()
    {
        CalculateLayoutInputHorizontal();
        float startX = -groupWidth / 2;
        for (int i=0; i<m_RectChildren.Count; i++)
        {
            var rect = m_RectChildren[i];
            rect.anchoredPosition = new Vector2(startX, 0);
            startX += spacing + rect.rect.width;
        }
    }

    private void Reset()
    {
        UpdateLayout();
    }
}

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号