Unity - NGUIのUIGridオブジェクトに子供を追加したときの位置調整

NGUIのUIGridは、その配下のオブジェクトを綺麗に並べてくれる便利なスクリプトだけれど、何も考えず動的に子供を追加したら位置調整機能が動かなかった話。


例えば、

using UnityEngine;

~~~

GameObject parent = GameObject.Find("Parent").transform;
GameObject object = Object.Instantiate(BaseObject) as GameObject;

object.transform.parent = parent.transform;
object.transform.localScale = new Vector3(1,1,1);
object.name = "Child";

こんな感じにBaseObjectのコピーを作って、UIGridを持つParentに追加したとする。これではobjectの位置はうまく調整されない。


UIGridのAddChild(Transform trans)を持ちうるべし。

// object.transform.parent = parent.transform;
parent.GetComponent<UIGrid>().AddChild(object.transform);


AddChildは、transform.parentを設定した後、ResetPositionを呼び出して位置を調整する。
いくつも子供を追加する場合は無駄にResetPositionされてしまうので、parentを自分で設定した後、Repositionを呼び出す。

for ( int i = 0; i < 10; i++ )
  {
    GameObject object = Object.Instantiate(BaseObject) as GameObject;
    object.transform.parent = parent.transform;
  }

parent.GetComponent<UIGrid>().Reposition()