LoginSignup
9
3

More than 3 years have passed since last update.

【Unity】Buttonのサイズをスクリプトから変更する

Last updated at Posted at 2019-04-10

UI系の配置はuGUIのAutoLayoutに任せたいが、場合によってはボタンのサイズをスクリプトから変更する必要があったりする。調べてみるとRectTransform.sizeDeltaを使用すればよいみたいな記事を発見したのだが、これではうまくいかない場合もあった。

RectTransform.sizeDeltaだとどうダメか

こんな風にCanvas直下にボタンを配置してボタンのサイズを300x200に変更してみる。
スクリーンショット 2019-04-10 10.23.16.png

Buttonに以下のスクリプトをアタッチする。

うまく行かない場合がある.cs
using UnityEngine;
using UnityEngine.UI;

public class ButtonSizeFitter : MonoBehaviour
{
    void Start()
    {
        // ボタンのサイズを300x200に変更する
        var targetSize = new Vector2(300, 200);
        GetComponent<RectTransform>().sizeDelta = targetSize;
    }
}

これだとButtonのアンカーがどこにあるかで結果が異なってしまう。

アンカーがボタン中央の場合

スクリーンショット 2019-04-10 10.33.22.png

Buttonのサイズそのものが300x200に変更されてうまくいく。

アンカーが四隅の場合

スクリーンショット 2019-04-10 10.33.56.png

Buttonのサイズが親のCanvasより大きくなってしまい、望んだ結果とは違ってしまう。

なぜこうなる

公式に書いてある。

で、どうやった解決するかと言うと、RectTransform.SetSizeWithCurrentAnchorsを使えば良いらしい。

RectTransform.SetSizeWithCurrentAnchorsで解決

SetSizeWithCurrentAnchorsを使用すると現在のアンカーの設定を考慮してサイズを変更してくれ、アンカーが中央だろうが四隅だろうが、同じ結果になった。

public class ButtonSizeFitter : MonoBehaviour
{
    void Start()
    {
        var rtf = GetComponent<RectTransform>();
        // 横方向のサイズ
        rtf.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 300);
        // 縦方向のサイズ
        rtf.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 200);
    }
}

9
3
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
9
3