デジタルコンテンツの制作

nekosuko.jp

Unity(C#) ブログ 学習

【Unity】nGUIなどのRectTransformのwidthやheightなどの値を変更する方法

更新日:

UnityのnGUIのレイアウトはRectTransformで管理されているようです。
x位置やy位置、widthやheightはこのRectTransformの中にあります。そこで、RectTransfrom.rectとやるとrect型のクラスを取得でき、その中にあるx位置、y位置、width、heightを取得できます。
ところが、widthやheightを変更しようとしても、固定されている的なエラーが出て変更できません。

widthやheightの変更はsizeDeltaを使用する

RectTransformのwidthやheightを変更したい場合は、RectTransformにあるVector2型のクラスsizeDeltaを変更します。
このsizeDeltaのなかにxとyがあり、それぞれwidthとheightに対応しているようです。

Vector2 sd = GetComponent<RectTransform>().sizeDelta;
sd.x *= 2;
GetComponent<RectTransform>().sizeDelta = sd;

これでwidthが倍になる(はず)。

x座標とy座標の変更 2015-6-2追記

座標の変更は同じRectTransformプロパティのanchoredPositionで変更できます。

Vector2 pos = GetComponent<RectTransform>().anchoredPosition;
pos.x *= 2;
GetComponent<RectTransform>().anchoredPosition = pos;

これでx位置が右に2倍移動している(はず)。

Lef・Top・Right・Bottomの変更 2018-1-23追記

Anchor PresetsをStrechにすると、RectTransformの値はLeftやTopになります。
これらの値を変更するときは、直接値を代入できるようです。

GetComponent<RectTransform>().offsetMin = new Vector2 (left,bottom);
GetComponent<RectTransform>().offsetMax = new Vector2 (right,top);

上記のleft、bottom、right、topがそれぞれの値に該当します。

以上

-Unity(C#), ブログ, 学習

Copyright© nekosuko.jp , 2024 All Rights Reserved.