Created
April 16, 2021 22:06
-
-
Save Tymski/652c6b47e79bfaf773f2bff8ebd43e97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
/// <summary> | |
/// Use a number of cells and columns instead of cell width and height | |
/// </summary> | |
[RequireComponent(typeof(GridLayoutGroup))] | |
[ExecuteInEditMode] | |
public class GridLayoutGroupCells : MonoBehaviour | |
{ | |
GridLayoutGroup gridLayoutGroup; | |
RectTransform rectTransform; | |
[SerializeField] int columns = 0; | |
[SerializeField] int rows = 0; | |
private void Awake() | |
{ | |
gridLayoutGroup = GetComponent<GridLayoutGroup>(); | |
rectTransform = GetComponent<RectTransform>(); | |
} | |
private void Update() | |
{ | |
CalculateCellSize(); | |
} | |
void CalculateCellSize() | |
{ | |
float cellWidth = rectTransform.rect.width; | |
if (columns > 0) | |
{ | |
cellWidth -= gridLayoutGroup.padding.left; | |
cellWidth -= gridLayoutGroup.padding.right; | |
cellWidth -= gridLayoutGroup.spacing.x * (columns - 1); | |
cellWidth -= float.Epsilon * 2; | |
cellWidth /= columns; | |
} | |
float cellHeight = rectTransform.rect.height; | |
if (rows > 0) | |
{ | |
cellHeight -= gridLayoutGroup.padding.top; | |
cellHeight -= gridLayoutGroup.padding.bottom; | |
cellWidth -= gridLayoutGroup.spacing.y * (rows - 1); | |
cellHeight -= float.Epsilon * 2; | |
cellHeight /= rows; | |
} | |
gridLayoutGroup.cellSize = new Vector2( | |
cellWidth, | |
cellHeight | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment