using UnityEngine; [ExecuteAlways] [RequireComponent(typeof(Camera))] public class CameraLetterbox : MonoBehaviour { public float targetAspect = 16f / 9f; private int lastWidth; private int lastHeight; void OnEnable() { ApplyLetterbox(); lastWidth = Screen.width; lastHeight = Screen.height; } void Update() { if (Screen.width != lastWidth || Screen.height != lastHeight) { ApplyLetterbox(); lastWidth = Screen.width; lastHeight = Screen.height; } } void ApplyLetterbox() { Camera cam = GetComponent(); float screenAspect = (float)Screen.width / Screen.height; float scaleHeight = screenAspect / targetAspect; if (scaleHeight < 1.0f) { cam.rect = new Rect( 0, (1f - scaleHeight) / 2f, 1, scaleHeight ); } else { float scaleWidth = 1f / scaleHeight; cam.rect = new Rect( (1f - scaleWidth) / 2f, 0, scaleWidth, 1 ); } } }