LoginSignup
6
3

More than 5 years have passed since last update.

【Unity uGUI】AutoLayout UIのRect Transformの値をスクリプトから取得する

Last updated at Posted at 2017-04-05

Horizontal Layout GroupやGrid Layout Groupなどの、AutoLayout UIのGameObjectのRect Transformをスクリプト側から取得したい時に、Start()で取得しようとした時に、正しい値が返ってこなかったので、メモ。
Unity Versionは5.6。

正しい値が取得できない↓

public RectTransform TargetUi;
private Vector3 _targetUiInWorldSpace;

private void Start()
{
    _targetUiInWorldSpace = Camera.main.ScreenToWorldPoint(TargetUi.position);
}

これはマニュアルにあるように、フレームの最後にAuto LayoutのRebuildが走り、描画位置が決定するためっぽい。

The rebuild will not happen immediately, but at the end of the current frame, just before rendering happens.

Start()などで正しい初期値を取得しておきたい場合は、WaitForEndOfFrameでフレームの最後まで待つことで取得することができました。

正しい値が取得できる↓

public RectTransform TargetUi;
private Vector3 _targetUiInWorldSpace;

public IEnumerator Start()
{
    return GetAutoLayoutPosition();
}

private IEnumerator GetAutoLayoutPosition()
{
    yield return new WaitForEndOfFrame();
    _targetUiInWorldSpace = Camera.main.ScreenToWorldPoint(_ TargetUi.position);
    yield return null;
}

以上

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