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.

GetComponentsInChildrenで親オブジェクトを除いて取得する方法

Last updated at Posted at 2021-06-18

Unityを触り始めてつまずいたGetComponentsInChildrenについて

GetComponentsInChildrenは親オブジェクトも取得してしまうので子オブジェクトのみ取得する方法

Test1.cs
    using System.Linq;

    public GameObject parent;//親オブジェクト
    private void Start()
    {
        List<GameObject> child = new List<GameObject>(parent.GetComponentsInChildren<GameObject>())
            .Select(item => item.gameObject)//TransformをGameObjectに変換
            .Skip(1)//親オブジェクトをスキップ
            .ToList();//Listに変換
    }

見やすくするために改行しているが、Linqを使えば1行で取得できる

Unityを使い始めたころはこのように書いていた

Test2.cs
    public GameObject parent;//親オブジェクト
    private void Start()
    {
        GameObject[] child = new GameObject[parent.transform.childCount];//子オブジェクトの数で初期化
        for(int i = 0; i < child.Length; i++)
        {
            child[i] = parent.transform.GetChild(i).gameObject;//子オブジェクト取得
        }
    }
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?