0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Unity備忘録】スマホごとの画面比率に囚われないキャンバスの設定

Posted at

【Unity備忘録】スマホごとの画面比率に囚われないキャンバスの設定

✅ 環境

  • Unity 6000.0.47.f1
  • 2D

✅ 概要

全てUI(キャンバス)上でゲームを作成したは良いが、スマホごと画面の大きさがちがうからごちゃごちゃに。。。
そんな時にどんなスマホでも同じUIとする方法を備忘録としてまとめます。

対応前:画面の大きさによってUIが画面外へ
マイビデオ.gif

対応後:どんな画面の大きさでも崩れない
マイビデオ-1.gif


✅ 対応

1. カメラのアスペクト比を任意の物に固定する

今回は16:9にする。
下記スクリプトを対象のカメラにアタッチ(キャンバスのレンダーカメラとして設定するカメラ)

AspectRatioFitterCamera.cs
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

[ExecuteAlways]
public class AspectRatioFitterCamera : MonoBehaviour
{
    // アスペクト比を設定
    [SerializeField] private float targetAspect = 16f / 9f;
    // 対象のカメラを設定(複数使用する時のために配列で定義)
    [SerializeField] private Camera[] targetCameras;

    void Awake()
    {
        // ゲーム開始時一度実行
        ApplyAspect();
    }

#if UNITY_EDITOR
    void Update()
    {
        // Unityエディタ編集モードのときだけ毎フレーム適用(調整しやすいように)
        if (!EditorApplication.isPlayingOrWillChangePlaymode)
        {
            ApplyAspect();
        }
    }
#endif

    // アスペクト比変更
    private void ApplyAspect()
    {
        if (targetCameras == null || targetCameras.Length == 0) return;

        float screenAspect = (float)Screen.width / Screen.height;

        if (screenAspect > targetAspect)
        {
            float inset = 1f - targetAspect / screenAspect;
            foreach (var cam in targetCameras)
            {
                cam.rect = new Rect(inset / 2f, 0, 1f - inset, 1f);
            }
        }
        else
        {
            float inset = 1f - screenAspect / targetAspect;
            foreach (var cam in targetCameras)
            {
                cam.rect = new Rect(0, inset / 2f, 1f, 1f - inset);
            }
        }
    }
}

◆インスペクターから設定
(TargetAspectが計算後になっちゃってるから縦横で変数作ってSerializeFieldの方がいいな。。)
image.png

2.キャンバス設定

・Canvasのレンダーモードを「スクリーンスぺ―ス - カメラ」に設定
・レンダーカメラに対象のカメラをアサイン
・CanvasScalerのUIスケールモードを「画面サイズに拡大」に設定
・参照解像度をゲーム画面を見ながら設定ちょうどよい所に設定する。
 →今回はx:2048,y:1152
・スクリーンマッチモードを「Match Width Or Height」に設定
・マッチを0(縦画面の場合は1)に設定
image.png

✅ 結果

以上でどのスマホでも見た目が崩れないキャンバスの完成

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?