ヒエラルキーのオブジェクト取得

Unity

ヒエラルキーにある全てのオブジェクト取得

    void Start()
    {
        // ヒエラルキー上のすべてのオブジェクトを取得
        Object[] allGameObject = Resources.FindObjectsOfTypeAll(typeof(GameObject));

        // 取得したオブジェクトの名前を表示
        foreach (GameObject obj in allGameObject)
        {
            Debug.Log(obj.name);
        }
    }

ヒエラルキーのルートにあるオブジェクトを取得

    void Start()
    {
        // using UnityEngine.SceneManagement の追加を忘れないように
        // シーンを取得
        Scene scene = SceneManager.GetSceneByBuildIndex(0);

        // 取得したシーンのルートにあるオブジェクトを取得
        GameObject[] rootObjects = scene.GetRootGameObjects();

        // 取得したオブジェクトの名前を表示
        foreach (GameObject obj in rootObjects)
        {
            Debug.Log(obj.name);
        }
    }

自分の子を1つ取得

    void Start()
    {
        // 自分の子を取得
        Transform child = transform.GetChild(0);

        // 取得したオブジェクトの名前表示
        Debug.Log(child.name);
    }

自分より下の階層を全て取得

    void Start()
    {
        // 自分の子を全て取得
        Transform[] children = gameObject.GetComponentsInChildren<Transform>();

        // 取得したオブジェクトの名前表示
        foreach (Transform obj in children)
        {
            Debug.Log(obj.name);
        }
    }

自分の1つ下の階層のみ全て取得

    void Start()
    {
        // 自分の1つ下の階層にオブジェクトがいくつあるか
        int count = transform.childCount;

        // 自分の1つ下の階層のオブジェクトを全て取得
        for (int i = 0; i < count; i++)
        {
            Transform child = transform.GetChild(i);

            // 取得したオブジェクトの名前を表示
            Debug.Log(child.name);
        }
    }

自分の親(ルート階層)オブジェクトを取得

    void Start()
    {
        // 自分の親(ルート)のオブジェクト取得
        Transform parent = transform.root;

        // 取得したオブジェクトの名前表示
        Debug.Log(parent.name);
    }

自分の親(1つ上)のオブジェクトを取得

    void Start()
    {
        // 自分の親(1つ上)のオブジェクト取得
        Transform parent = transform.parent;

        // 取得したオブジェクトの名前表示
        Debug.Log(parent.name);
    }

以上!

コメント

タイトルとURLをコピーしました