4
7

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 5 years have passed since last update.

【Unity】子の要素をFindを使わずにFor文で取得する。

Last updated at Posted at 2019-08-28

はじめに(追記)

追記 : コメントでさらにスマートな処理を書いていただいたので、そちらも併せて紹介しておきます。


GameObjectをFindで取得するには、当然Findするオブジェクトを指定しなければいけないため、
取得したいオブジェクトの数だけ分が増えます。これが数が増えてくると面倒くさい...。

気付けばこんな事に...
コメント 2019-08-28 144732.png

これをなんとか解消したいと思い、色々試した結果For文を使って短く、それでいて管理が楽にできたので
記事としてまとめようと思った次第です。

Script(追記)

**追記 :**追記のスクリプト

GetChildNext.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GetChild : MonoBehaviour
{
    public GameObject[] Parents;
    List<GameObject> Paneles;

    void Start()
    {
        Paneles = new List<GameObject>();

        foreach(GameObject p in Parents)
        {
            foreach(Transform child in p.transform)
            {
                Paneles.Add(child.gameObject);
            }
        }

        for(int i = 0; i < Paneles.Count; i++)
        {
            Debug.Log(Paneles[i]);
        }
    }
}

この処理では親を1、子を2、子の子を3としたとき、Parentsにセットしている子を取得するので、
1をセットしている場合、2のオブジェクトは取得されるが、3は取得されません。
(下のGetChild.csでも同じです)

3を取得したい場合は2をセットすれば取得できます。


GetChild.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GetChild : MonoBehaviour
{
    public GameObject[] Parents;
    GameObject Panel;
    List<GameObject> Paneles;

    void Start()
    {
        Paneles = new List<GameObject>();

        for(int v = 0; v < Parents.Length; v++)
        {
            for(int i = 0; i < Parents[v].transform.childCount; i++ )
            {
                Panel = Parents[v].transform.GetChild(i).gameObject;
                Paneles.Add(Panel);
            }
        }

        for(int i = 0; i < Paneles.Count; i++) //確認用の表記
        {
            Debug.Log(Paneles[i]);
        }
    }
}

たったこれだけです。

使い方は以下の通りです。

1、何らかのオブジェクトにアタッチする
2、子を取得したい親オブジェクトをParentsインスペクターにセット
 (Sizeを変更すればセットできる数も増えます)
コメント 2019-08-28 144732.png

さいごに

この方法を考え付いたのは、インターフェースの記事を見ていて、こういう感じにうまく
まとめられないかなぁ~という漠然とした思い付きで試してみた結果、
「なんかできたわ」という感じでした。

自分の知識量が以前に比べて増えているんだなぁという実感を得られたので良かったです。
この方法が誰かの役に立ちますように。

4
7
2

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
4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?