Unityで非アクティブのGameObjectをスクリプトで取得(Find)する方法について説明します。
広告
FindObjectsType<GameObject>(true)
FindObjectsTypeの引数にtrueを渡すことで、非アクティブのGameObjectも取得します。
public static Object[] FindObjectsOfType(Type type); public static Object[] FindObjectsOfType(Type type, bool includeInactive); public static T[] FindObjectsOfType(bool includeInactive); public static T[] FindObjectsOfType();
// 全てのGameObjectを取得する(非アクティブのGameObjectを含む) var gos = FindObjectsOfType<GameObject>(true); // 引数にtrueを渡して、非アクティブのGameObjectも含ませる // 取得した全てのGameObjectの中から"Test"という名前のGameObjectを探す foreach (var go in gos) { if(go.name == "Test") { // 処理 Debug.Log("Testが見つかりました。"); break; } }
非アクティブのGameObjectのComponentを取得する引数を持つメソッドは、他にGetComponentsInChildrenなどがあります。
parentGameObject.transform.Find(“Name”).gameObject
探したいGameObjectの親がわかっていれば、以下の記述で非アクティブのGameObjectでも取得できます。
// parentGameObjectは探したいGameObjectの親のGameObject var go = parentGameObject.transform.Find("Test").gameObject;
このメソッドで、親を持たない非アクティブのGameObjectを取得できるか調べてみましたが、調べた限りではできなさそうでした。
アクティブにしておいて、スクリプトで取得してから非アクティブにする
private GameObject testGameObject; void Start(){ testGameObject = GameObject.Find("Test"); testGameObject.SetActive(false); }
Inspectorでアサインする
あらかじめInspectorでアサインしておく方法もあります。
[SerializeField] private GameObject testGameObject; // Inspectorでアサインする
広告
おわりに
FindObjecsOfType<GameObject>(true)を紹介している人がいなかったので記事にしました。参考になれば幸いです。