鸟语天空
UGUI—布局组(LayoutGroup)
post by:追风剑情 2021-12-8 10:50

一、水平居中布局

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();
    }
}

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容