工作中经常需要用到Grid,动态添加物体时,就需要动态改变Grid大小。直接写好脚本,以后COPY。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class Colve_UpdateGridShow : MonoBehaviour {
public GridLayoutGroup m_Grid;
private Vector2 cellVec2;
private Vector2 spacSize;
private RectOffset padding;
private GridType m_GridType;
private Vector2 m_SizeDelta;
private RectTransform m_Transform;
private void GetMessage()
{
m_Grid = GetComponent<GridLayoutGroup> ();
m_Transform = GetComponent<RectTransform> ();
cellVec2 = m_Grid.cellSize;
m_SizeDelta = m_Transform.sizeDelta;
spacSize = m_Grid.spacing;
padding = m_Grid.padding;
ChangeType ();
}
private void ChangeType()
{
switch (m_Grid.startAxis)
{
case GridLayoutGroup.Axis.Horizontal:
m_GridType = GridType.Horizontal;
break;
case GridLayoutGroup.Axis.Vertical:
m_GridType = GridType.Vertical;
break;
default:
break;
}
}
/// <summary>
/// 动态改变Grid大小
/// </summary>
[ContextMenu("UpdateShow")]
public void Update_Show()
{
GetMessage ();
switch (m_GridType)
{
case GridType.Horizontal:
ChangeSize_Horizontal();
break;
case GridType.Vertical:
ChangeSize_Vertical();
break;
default:
break;
}
}
private void ChangeSize_Horizontal()
{
int columnCount = Mathf.FloorToInt((m_SizeDelta.x - cellVec2.x - padding.left - padding.right) / (cellVec2.x + spacSize.x)) + 1;
int rowCount = Mathf.CeilToInt((float)transform.childCount / columnCount);
m_Transform.sizeDelta = new Vector2 (m_Transform.sizeDelta.x, (rowCount * cellVec2.y) + ((rowCount - 1) * spacSize.y) + padding.top + padding.bottom);
}
private void ChangeSize_Vertical()
{
int columnCount = Mathf.FloorToInt((m_SizeDelta.y - cellVec2.y - padding.top - padding.bottom) / (cellVec2.y + spacSize.y)) + 1;
int rowCount = Mathf.CeilToInt((float)transform.childCount / columnCount);
m_Transform.sizeDelta = new Vector2 ((rowCount * cellVec2.x) + ((rowCount - 1) * spacSize.x) + padding.left + padding.right,m_Transform.sizeDelta.y);
}
}
public enum GridType
{
Horizontal,
Vertical
}