LoginSignup
81

More than 5 years have passed since last update.

【Unity】スクリプトからオブジェクトやコンポーネント操作まとめ

Last updated at Posted at 2013-06-28

Unity3dのシーン内に表示されるオブジェクトはすべてGameObjectで構成されている。
細部項目はComponentに含まれ階層になっている。

空GameObjectを作り、さまざま項目を追加し、利用できる。
必要なオブジェクトを作り管理しやすい。

だけど、スクリプト上、各オブジェクトを操作があいまいな場合があって
これについて知っている限りメモみたいな感じで書く。

HierarchyでGameObject探し

グローバルメソッドのGameObject.Find() / GameObject.FindWithTag() で探す
GameObject obj = GameObject.Find( typeof(MyObject) );
GameObject obj = GameObject.FindWithTag("MyObjectTag");

親子オブジェクトの操作

GameObjectは子オブジェクトや親オブジェクトの情報を持っている
実際はGameObjectよりGameObjectのコンポーネントのTransFormオブジェクトが持っている
Transformはworld positionやlocal positionなどを管理するやつだから
このオブジェクトを使って親オブジェクトや子オブジェクトを得られる。

GameObject child = transform.Find("ChildObject").gameObject;
GameObject parent = transform.parent.gameObject;
GameObject child2 = transform.Find("Child/ChildObject").gameObject;

スクリプト操作

GameObjectまでつなぐと含まれたコンポーネントはGetComponentで探す
MyBehaviour myScript = (MyBehaviour) child.GetComponent( typeof( MyBehaviour ) );
myScript.Something();

親子オブジェクトリスト

子オブジェクトを配列で取ってきて順である作業をするときに使う

Transform[] objList = gameObject.GetComponentsInChildren(typeof(Transform));
foreach( Transform child in objList ) {
child.gameObject.GetComponent( ....);
}

20150301追記
// ジェネリックバージョン(要using System.Collections.Generic;)
Transform[] objList = gameObject.GetComponentsInChildren();
// 子オブジェクトリストが非アクティブの場合はパラメータ(true)を渡せば取得可能
Transform[] objList = gameObject.GetComponentsInChildren(true);

20140323追記
// 子Transform数を取得し、index順でループを回す
for (int i = 0; i < this.transform.childCount; i++) {
GameObject go = transform.GetChild(i).gameObject;
}

// 子Transformのコンポーネントをすべて取得し、ループで回す
Transform[] objList = GameObject.FindGameObjectWithTag("BlockList").GetComponentsInChildren();
foreach( Transform child in objList ) {
child.transform.position = new Vector2(child.transform.position.x, child.transform.position.y + 1);
}

オブジェクトの活性化/非活性化

初期は非活性化状態である瞬間、各オブジェクトを活性化する必要がある。
この場合は各オブジェクトを探してactive = true; にするときに

gameObject.SetActiverecursively( true );

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
81