using UnityEngine; using UnityEngine.UI; /// /// RawImage 의 텍스처가 런타임에 교체될 때 AspectRatioFitter 의 종횡비를 그 텍스처에서 다시 읽어온다. /// /// 왜 필요한가 (#800): /// 로딩 배경은 Addressables 로 Loading1~8 중 하나를 매번 새로 불러와 RawImage.texture 에 꽂는다. /// AspectRatioFitter.aspectRatio 는 직렬화된 상수라, 나중에 종횡비가 다른 이미지가 한 장이라도 /// 추가되면 그 장만 조용히 늘어난다(=이번에 PD 가 지적한 "비율 어긋남"의 재발). /// 종횡비를 "이미지에서 파생"시키면 그 클래스의 회귀가 구조적으로 사라진다. /// /// 비용: 텍스처 참조 1회 비교/프레임. 이 오브젝트는 로딩 화면이 떠 있는 동안에만 활성이다. /// [ExecuteAlways] [RequireComponent(typeof(RawImage))] [RequireComponent(typeof(AspectRatioFitter))] [DisallowMultipleComponent] public class WLRawImageAspectSync : MonoBehaviour { [Tooltip("텍스처가 아직 없을 때 쓸 종횡비 (가로/세로). 원본 1920x1080 = 1.7778")] public float fallbackRatio = 16f / 9f; RawImage _raw; AspectRatioFitter _fitter; Texture _applied; void OnEnable() { _raw = GetComponent(); _fitter = GetComponent(); _applied = null; // 활성화될 때마다 무조건 한 번 맞춘다 Sync(); } void LateUpdate() { Sync(); } #if UNITY_EDITOR void OnValidate() { if (isActiveAndEnabled) Refresh(); } #endif /// 텍스처를 방금 코드로 바꿔치기했을 때처럼, 다음 프레임을 기다리지 않고 즉시 반영해야 할 때 부른다. public void Refresh() { _raw = GetComponent(); _fitter = GetComponent(); _applied = null; Sync(); } void Sync() { if (_raw == null || _fitter == null) return; var tex = _raw.texture; if (tex == _applied) return; // 대부분의 프레임은 여기서 끝난다 _applied = tex; float ratio = (tex != null && tex.height > 0) ? tex.width / (float)tex.height : fallbackRatio; if (ratio <= 0f) ratio = fallbackRatio; if (!Mathf.Approximately(_fitter.aspectRatio, ratio)) _fitter.aspectRatio = ratio; } }