ThreeKingdomsSlingshot/Assets/Scripts/OutGame/UI/UiAutoGrid.cs

59 lines
2.3 KiB
C#

using UnityEngine;
using UnityEngine.UI;
namespace TKS.OutGame
{
/// <summary>
/// 해상도 대응 카드 격자(PD 2026-11-09 「한 줄 최대 4명 · 가로가 길면 4명 이상 · 좁으면 3명 · 자동 리사이징」) —
/// 폭에 맞춰 열 수 = round((폭 + 간격) ÷ (목표 칸 폭 + 간격)) · 최소 minColumns · 칸 폭 = 폭을 열 수로 나눔(세로 = 원래 비율) ·
/// 각 칸(holder)의 첫 자식 = 원래 크기(design) 카드 → 배율 Scale 로 맞춤. 기준 1080 폭(좌우 24) = 4열.
/// </summary>
[RequireComponent(typeof(GridLayoutGroup))]
public class UiAutoGrid : MonoBehaviour
{
public Vector2 design = new Vector2(320f, 431f);
public float targetWidth = 246f;
public float gap = 16f;
public int minColumns = 3;
GridLayoutGroup grid;
bool busy;
public float Scale { get; private set; }
public int Columns { get; private set; }
void Awake()
{
grid = GetComponent<GridLayoutGroup>();
if (Scale <= 0f) Scale = targetWidth / design.x;
}
void OnRectTransformDimensionsChange()
{
Apply();
}
/// <summary>지금 폭으로 열 수·칸 크기·카드 배율을 다시 계산(칸을 새로 넣은 뒤에도 부른다).</summary>
public void Apply()
{
if (busy) return;
if (grid == null) Awake();
var rt = (RectTransform)transform;
float w = rt.rect.width - grid.padding.left - grid.padding.right;
if (w <= 1f) return;
busy = true;
int cols = Mathf.Max(minColumns, Mathf.RoundToInt((w + gap) / (targetWidth + gap)));
float cw = (w - (cols - 1) * gap) / cols;
Scale = cw / design.x;
Columns = cols;
var cell = new Vector2(cw, design.y * Scale);
if (grid.cellSize != cell) grid.cellSize = cell;
if (grid.spacing != new Vector2(gap, gap)) grid.spacing = new Vector2(gap, gap);
if (grid.constraintCount != cols) grid.constraintCount = cols;
foreach (Transform c in transform)
if (c.childCount > 0) c.GetChild(0).localScale = new Vector3(Scale, Scale, 1f);
busy = false;
}
}
}