バージョン
- Unity 2022.3.45f1
ゲームオブジェクトの位置とサイズを取得・変更する方法です。
UIオブジェクト
スクリプト
UIオブジェクトはRectTransformから次のコードで取得します。
//位置
Vector2 pos = gameObject.GetComponent<RectTransform>().anchoredPosition;
float posX = pos.x; //X座標
float posY = pos.y; //Y座標
//サイズ
Vector2 size = gameObject.GetComponent<RectTransform>().sizeDelta;
float width = size.x; //幅
float height = size.y; //高さ
ワールド座標で取得したい場合はこちら。
//位置(ワールド座標)
Vector2 worldPos = gameObject.GetComponent<RectTransform>().position;
float worldPosX = worldPos.x; //X座標
float worldPosY = worldPos.y; //Y座標
検証
実際に位置とサイズを取得した後、倍の数値に変更してみます。
RectTransform rectTransform = GetComponent<RectTransform>();
Vector2 pos = rectTransform.anchoredPosition;
Vector2 size = rectTransform.sizeDelta;
Debug.Log($"Pos X:{pos.x}, Pos Y:{pos.y}, Width:{size.x}, Height:{size.y}");
pos *= 2f;
size *= 2f;
//位置変更
rectTransform.anchoredPosition = pos;
//サイズ変更
rectTransform.sizeDelta = size;
Vector2 newPos = rectTransform.anchoredPosition;
Vector2 newSize = rectTransform.sizeDelta;
Debug.Log($"Pos X:{newPos.x}, Pos Y:{newPos.y}, Width:{newSize.x}, Height:{newSize.y}");
変更前

変更後


3Dオブジェクト
スクリプト
3DオブジェクトはTransformから次のコードで取得します。
//位置
Vector3 pos = transform.position;
float posX = pos.x; //X座標
float posY = pos.y; //Y座標
float posZ = pos.z; //Z座標
//スケール
Vector3 scale = transform.localScale;
float width = scale.x; //幅
float height = scale.y; //高さ
float depth = scale.z; //奥行き
実際のサイズを取得したい場合はこちら。
//サイズ
Vector3 size = gameObject.GetComponent<Renderer>().bounds.size;
float width = size.x; //幅
float height = size.y; //高さ
float depth = size.z; //奥行き
検証
以下のコードで位置とスケールを取得した後、3倍に変更してみます。
Vector3 pos = transform.position;
Vector3 scale = transform.localScale;
Debug.Log($"Pos X:{pos.x}, Pos Y:{pos.y}, Pos Z:{pos.z}, Width:{scale.x}, Height:{scale.y}, Depth:{scale.z}");
pos *= 3;
scale *= 3;
//位置変更
transform.position = pos;
//スケール変更
transform.localScale = scale;
Vector3 newPos = transform.position;
Vector3 newScale = transform.localScale;
Debug.Log($"Pos X:{newPos.x}, Pos Y:{newPos.y}, Pos Z:{newPos.z}, Width:{newScale.x}, Height:{newScale.y}, Depth:{newScale.z}");
変更前

変更後


RectTransform - Unity スクリプトリファレンス
矩形の位置、サイズ、アンカー、ピボットの情報
Transform - Unity スクリプトリファレンス
オブジェクトの位置、回転、スケールを扱うクラス