Last active
May 23, 2021 23:09
-
-
Save bpicolo/d7c73f3e39d91822f3984ecc134dd302 to your computer and use it in GitHub Desktop.
Dynamic Grid Scaling for Unity UI grids
This file contains hidden or 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; | |
using System.Collections; | |
/** | |
* Scale a GridLayoutGroup according to resolution, etc. | |
* This is using width-constrained layout | |
*/ | |
public class GridScalar : MonoBehaviour { | |
private GridLayoutGroup grid; | |
private RectOffset gridPadding; | |
private RectTransform parent; | |
public int rows = 6; | |
public int cols = 7; | |
public float spacing = 10; | |
Vector2 lastSize; | |
void Start () { | |
grid = GetComponent<GridLayoutGroup>(); | |
grid.spacing = new Vector2(spacing, spacing); | |
parent = GetComponent<RectTransform>(); | |
gridPadding = grid.padding; | |
lastSize = Vector2.zero; | |
} | |
// Update is called once per frame | |
void Update () { | |
if (lastSize == parent.rect.size) | |
{ | |
return; | |
} | |
var paddingX = gridPadding.left + gridPadding.right; | |
var cellSize = Mathf.Round((parent.rect.width - paddingX - (rows - 1) * spacing) / rows); | |
grid.cellSize = new Vector2(cellSize, cellSize); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment