コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】すべての子オブジェクトを取得する拡張メソッド

概要

f:id:baba_s:20140728191228p:plain

例えばこれらのオブジェクトが Hierarchy に存在する場合に
UIRoot の子オブジェクトをすべて取得したい時があったので
指定したゲームオブジェクトやコンポーネントの子オブジェクトを
すべて取得するための拡張メソッドを作成しました

using System.Linq;
using UnityEngine;

public static class GameObjectExtensions
{
    /// <summary>
    /// すべての子オブジェクトを返します
    /// </summary>
    /// <param name="self">GameObject 型のインスタンス</param>
    /// <param name="includeInactive">非アクティブなオブジェクトも取得する場合 true</param>
    /// <returns>すべての子オブジェクトを管理する配列</returns>
    public static GameObject[] GetChildren( 
        this GameObject self, 
        bool includeInactive = false )
    {
        return self.GetComponentsInChildren<Transform>( includeInactive )
            .Where( c => c != self.transform )
            .Select( c => c.gameObject )
            .ToArray();
    }
}
    
public static class ComponentExtensions
{
    /// <summary>
    /// すべての子オブジェクトを返します
    /// </summary>
    /// <param name="self">Component 型のインスタンス</param>
    /// <param name="includeInactive">非アクティブなオブジェクトも取得する場合 true</param>
    /// <returns>すべての子オブジェクトを管理する配列</returns>
    public static GameObject[] GetChildren( 
        this Component self, 
        bool includeInactive = false )
    {
        return self.GetComponentsInChildren<Transform>( includeInactive )
            .Where( c => c != self.transform )
            .Select( c => c.gameObject )
            .ToArray();
    }
}
using UnityEngine;

public class UIRoot : MonoBehaviour
{
    private void Awake()
    {
        // すべての子オブジェクトを取得します
        foreach ( var n in gameObject.GetChildren() )
        {
            Debug.Log( n.name );
            // Base
            // Button
        }
        
        // すべての子オブジェクトを取得します(非アクティブも含む)
        foreach ( var n in gameObject.GetChildren( true ) )
        {
            Debug.Log( n.name );
            // Base
            // Button
            // Label
        }
    }
}

関連記事