forked from cjacobwade/HelpfulScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GridLayoutDynamicSize.cs
59 lines (48 loc) · 1.47 KB
/
GridLayoutDynamicSize.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(GridLayoutGroup)), ExecuteInEditMode]
public class GridLayoutDynamicSize : MonoBehaviour
{
GridLayoutGroup _gridLayoutGroup = null;
GridLayoutGroup gridLayoutGroup
{
get
{
if (!_gridLayoutGroup)
_gridLayoutGroup = GetComponent<GridLayoutGroup>();
return _gridLayoutGroup;
}
}
RectTransform _rectTransform = null;
RectTransform rectTransform
{
get
{
if (!_rectTransform)
_rectTransform = GetComponent<RectTransform>();
return _rectTransform;
}
}
void LateUpdate()
{
UpdateCellSize();
}
protected void OnRectTransformDimensionsChange()
{
UpdateCellSize();
}
void UpdateCellSize()
{
int cellCount = gridLayoutGroup.GetComponentsInImmediateChildren<Transform>().Length;
int columnCount = cellCount == 2 ? 2 : Mathf.CeilToInt(((float)cellCount) / 2f);
int rowCount = cellCount > 2 ? 2 : 1;
float xPadding = gridLayoutGroup.padding.left + gridLayoutGroup.padding.right;
float yPadding = gridLayoutGroup.padding.top + gridLayoutGroup.padding.bottom;
float xSplits = (float)(columnCount - 1);
float ySplits = (float)(rowCount - 1);
Vector2 cellSize = Vector2.zero;
cellSize.x = rectTransform.rect.width/(float)columnCount - (xPadding + gridLayoutGroup.spacing.x * xSplits)/(float)columnCount;
cellSize.y = rectTransform.rect.height/(float)rowCount - (yPadding + gridLayoutGroup.spacing.y * ySplits)/(float)rowCount;
gridLayoutGroup.cellSize = cellSize;
}
}