Warning: Undefined array key 2 in /home/xs390735/increment-log.com/public_html/wp-content/themes/increment-log/functions.php on line 349
Warning: Undefined array key 4 in /home/xs390735/increment-log.com/public_html/wp-content/themes/increment-log/functions.php on line 354
Warning: Undefined array key 6 in /home/xs390735/increment-log.com/public_html/wp-content/themes/increment-log/functions.php on line 359
Prefabなどのインスタンスを生成するInstantiate()メソッドを使うとシーンにオブジェクトが出来上がります。これを特定のオブジェクトの入れ子にする方法について軽くメモ。
Instantiateで生成したオブジェクトを入れ子にする
方法はとっても簡単で、以下のようにtransformのparentに設定するだけです。
まず、何らかの方法で親オブジェクトを取得します。
// インスペクタから直接、親オブジェクトを指定するとか
public GameObject parentObject;
// タグ名から親オブジェクトを探して取得するとか
GameObject parentObject = GameObject.FindGameObjectWithTag("ParentObject");あとはインスタンス生成したオブジェクトの親を設定するだけです。
// prefabObjectにはプレハブが指定されているとします
GameObject childObject = Instantiate(prefabObject) as GameObject;
childObject.transform.parent = parentObject.transform;もし親にするオブジェクトのスクリプトでInstantiate()しているのなら、親オブジェクトを探す必要は無いので2行目は以下のように簡略化できます。
GameObject childObject = Instantiate(prefabObject) as GameObject;
childObject.transform.parent = this.transform;2行目の「this」は書いても書かなくても大丈夫です。
参考URL: How can I instantiate a GameObject directly into another GameObject as Child ? – Unity Answers