UGUI动态改变Grid大小

Posted Colve

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UGUI动态改变Grid大小相关的知识,希望对你有一定的参考价值。

工作中经常需要用到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
}

以上是关于UGUI动态改变Grid大小的主要内容,如果未能解决你的问题,请参考以下文章

unity ugui 怎么制作下拉动态刷新

如何将动态列宽设置为 AG-Grid?

UGUI 用脚本动态改变Button颜色组合

使用 Ag Grid 动态改变单元格颜色

WPF 动态插入grid 将Grid中的一个空白布局,用同样大小的一个Grid插入,怎么实现

具有动态大小的图像网格固定纵横比