Unity

Canvas Scale 해상도에 대응 적용하기

ㅎ-ㅎ 2023. 2. 18. 17:29

Canvas Scaler의 Reference Resolution을 넘어가면 Match를 1로 바꿔줌

- UI 배치는 세로 해상도 기준으로 하기(Match Width, 0에 가깝게 둔 상태로)

- Canvas Scaler의 Reference Resolution이 넘어가는 비율로, 가로가 더 넓어지면 Height에 가깝게 MatchWidthOrHeight를 1로 바꿔주도록 Canvas Scaler 달린 컴포넌트에 아래의 스크립트 달아주기

 

using UnityEngine;
using UnityEngine.UI;

[ExecuteInEditMode]
[RequireComponent(typeof(CanvasScaler))]
public class CanvasScalerController : MonoBehaviour
{
    private CanvasScaler scaler;
    private float referenceRatio;

    private void Awake()
    {        
        scaler = GetComponent<CanvasScaler>();
        UpdateMatchWithOrHeight();
    }

#if UNITY_EDITOR
    private void Update()
    {
        UpdateMatchWithOrHeight();
    }

    private void UpdateMatchWithOrHeight()
    {
        referenceRatio = scaler.referenceResolution.x / scaler.referenceResolution.y;

        if(referenceRatio < Camera.main.aspect)
        {
            scaler.matchWidthOrHeight = 1;
        }
        else
        {
            scaler.matchWidthOrHeight = 0;
        }
    }
#endif

}