首页 > 其他 > 详细

UGUI动态改变Grid大小

时间:2016-03-16 07:02:56      阅读:795      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/colve/p/5281931.html

(0)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!