創作世界のいろいろ〜AdobeとかC#とか

絵を描く人がC#とか3Dとか動画編集とかやる為の備忘録

【Unity】ゲーム内でパネルサイズを動的に変化させる

あらゆる端末の画面比率に対応するには、canvasでいろいろ設定すると思うのですが、それに限界を感じた時に、微調整はユーザーに委ねてしまおうと思いました。

 

準備

canvasやpanel、sliderを用意します。

 

スクリプトの作成

基準値になるスクリーンのアスペクト比を取得するスクリプトを作成します。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AspectCheckerController : MonoBehaviour
{
   public float widthScreenSize;
   public float heightScreenSize;
   public float aspectRatio;

   public void CalculateAspectRatio()
    {
        // カメラを取得
        Camera cameraToUse = Camera.main; // メインカメラを指定
        //任意のカメラを指定するならSerializeField

        widthScreenSize = Screen.width;
        heightScreenSize = Screen.height;
        // カメラのアスペクト比を計算
        aspectRatio = (float)Screen.width / Screen.height;
    }
}

これを、先ほどの空のゲームオブジェクト(画像のAspectChecker)にアタッチします。

 

スライダーで調整するためのスクリプトを作成

下記の通り。

using UnityEngine;
using UnityEngine.UI;

public class PanelSizeController : MonoBehaviour
{
    AspectCheckerController aspectCheckerController;
    [SerializeField] GameObject AspectChecker;
  [SerializeField] Slider slider; GameObject selfObject; string selfObjectName;//この辺はなくてもいい RectTransform selfObjectRect; float sliderMin; float sliderMax; // Start is called before the first frame update void Start() { aspectCheckerController = AspectChecker.GetComponent<AspectCheckerController>(); selfObject = gameObject; selfObjectName = gameObject.name;//この辺はなくてもいい selfObjectRect = selfObject.GetComponent<RectTransform>(); sliderMax = selfObjectRect.rect.height; sliderMin = selfObjectRect.rect.height * (float)0.5; slider.minValue = sliderMin; slider.maxValue = sliderMax; aspectCheckerController.CalculateAspectRatio(); } void Update() { selfObjectRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,slider.value);             selfObjectRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,slider.value * aspectCheckerController.aspectRatio); Debug.Log("ScreenSize: " + selfObjectRect.rect.width + "x" + selfObjectRect.rect.height ); } }

このスクリプトを、リサイズしたいパネル等にアタッチするだけ。

 

他にも色々やり方あると思うし、果たして有効性があるのか、まだわからないのですが、色々使えそうです。