Skip to content

Instantly share code, notes, and snippets.

@kuluna
Created November 15, 2025 06:59
Show Gist options
  • Select an option

  • Save kuluna/9e5194f832745c25dd01869e82232cf9 to your computer and use it in GitHub Desktop.

Select an option

Save kuluna/9e5194f832745c25dd01869e82232cf9 to your computer and use it in GitHub Desktop.
using UnityEngine;
[ExecuteAlways]
[RequireComponent(typeof(Camera))]
public class CameraRectScaler : MonoBehaviour
{
[SerializeField] private float targetAspect = 16f / 9f;
private int lastWidth = 0;
private int lastHeight = 0;
private Camera mainCamera;
private void Start()
{
TryGetComponent(out mainCamera);
ApplyRectScale();
}
private void Update()
{
// 画面サイズが変わった瞬間だけ再計算
if (Screen.width != lastWidth || Screen.height != lastHeight)
{
ApplyRectScale();
}
}
private void ApplyRectScale()
{
lastWidth = Screen.width;
lastHeight = Screen.height;
float windowAspect = (float)lastWidth / lastHeight;
float scale = windowAspect / targetAspect;
// 横長 → 左右に黒帯(ピラーボックス)
if (scale > 1f)
{
float newWidth = 1f / scale;
float xOffset = (1f - newWidth) / 2f;
mainCamera.rect = new Rect(xOffset, 0f, newWidth, 1f);
}
// 縦長 → 上下に黒帯(レターボックス)
else
{
float newHeight = scale;
float yOffset = (1f - newHeight) / 2f;
mainCamera.rect = new Rect(0f, yOffset, 1f, newHeight);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment