1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GetComponetsInChildren は孫も対象になるのか?

Last updated at Posted at 2021-01-11

Unity 初心者向けの記事です。

Unity で開発していて、画面上に表示している TextMeshPro の値を変更したい場合が出てくると思います。
動的に生成したオブジェクトの場合など、インスペクターから設定できない場合に、コンポーネントを検索して設定する場合などがあると思いますが、そういう場合の変更方法になります。

TL;DR

getComponetsInChildren は一段階下の階層だけではなく、さらに下の孫階層なども検索してくれます。
ので、孫にある TextMeshPro の文字を変更した場合も、GetComponetsChildren で取得した結果から変更することができます。

前提

  • Unity 2019.4.9f1

やったこと

流れ

1.こんな感じのGameObjectを準備しておきます
2020-12-28_13h10_17.png
2. 階層を検索して孫が取れることを確認しています
3. 孫が取れている前提で、TextMeshPro の文字の値を変更しています

サンプルプログラム

    [SerializeField] private GameObject root;
    private void TestGetComponentsInChildren()
    {
        var r = Instantiate(root);

        // 生成したオブジェクト(root)から、TextMeshPro を持っているオブジェクトを検索する
        var children = r.GetComponentsInChildren<TextMeshPro>();
        if (children == null)
        {
            Debug.Log("children is null");
        }
        else
        {
            Debug.Log("children is NOT null");
            Debug.Log(children.Length);
            // 今回は Leaf1 と Leaf2 が TextMeshPro を持っているので、
            // 1つ下の階層も2つ下の階層も検索してくれていれば Leaf1, Leaf2 と出力されます
            Debug.Log(string.Join(",", children.Select(x => x.gameObject.name)));
        }

        // ↑ で取得できている前提で、Leaf2 のオブジェクトを持ってきます
        var grandChild = children.First(c => c.gameObject.name == "Leaf2");
        if (grandChild == null)
        {
            Debug.Log("grandChild is null");
        }
        else
        {
            Debug.Log("grandChild is NOT null");
            grandChild.GetComponent<TextMeshPro>().text = "grandChild";
        }
    }

結果

コンソールには孫まで取れていることがわかるログが出つつ、
2020-12-28_13h27_34.png
Leaf2 の TextMeshPro には grandChild が設定されています。
2020-12-28_13h28_15.png

おまけ

  • name で指定して対象のオブジェクトを取得しているので、一文字でも間違っているとエラーになります。
1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?