コガネブログ

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

【Unity】GetComponentInChildren で引数の型情報を文字列で渡せるようにする拡張メソッド

ソースコード

using UnityEngine;

public static class GameObjectExt
{
    public static Component GetComponentInChildren( this GameObject self, string type, bool includeInactive )
    {
        var com = self.GetComponent( type );

        if ( com != null ) return com;

        foreach ( var n in self.GetComponentsInChildren<Transform>( includeInactive ) )
        {
            com = n.gameObject.GetComponent( type );

            if ( com != null ) return com;
        }

        return null;
    }
}

使い方

var com = gameObject.GetComponentInChildren( "BoxCollider" );