コガネブログ

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

【Unity】GetComponentInChildren の null チェックを少しだけ簡潔に記述できる TryGetComponentInChildren 拡張メソッド

ソースコード

using UnityEngine;

public static class ComponentExt
{
    public static bool TryGetComponentInChildren<T>( this Component self, out T component ) where T : Component
    {
        component = self.GetComponentInChildren<T>();
        return component != null;
    }
    
    public static bool TryGetComponentInChildren<T>( this Component self, out T component, bool includeInactive ) where T : Component
    {
        component = self.GetComponentInChildren<T>( includeInactive );
        return component != null;
    }
}

public static class GameObjectExt
{
    public static bool TryGetComponentInChildren<T>( this GameObject self, out T component ) where T : Component
    {
        component = self.GetComponentInChildren<T>();
        return component != null;
    }
    
    public static bool TryGetComponentInChildren<T>( this GameObject self, out T component, bool includeInactive ) where T : Component
    {
        component = self.GetComponentInChildren<T>( includeInactive );
        return component != null;
    }
}

使用例

通常

using UnityEngine;

public class Example : MonoBehaviour
{
    private void Awake()
    {
        var collider1 = GetComponentInChildren<BoxCollider>();
        if ( collider1 != null )
        {
            Debug.Log( collider1 );
        }
        var collider2 = GetComponentInChildren<BoxCollider>();
        if ( collider2 != null )
        {
            Debug.Log( collider2 );
        }
    }
}

拡張メソッド

using UnityEngine;

public class Example : MonoBehaviour
{
    private void Awake()
    {
        if ( this.TryGetComponentInChildren<BoxCollider>( out var collider1 ) )
        {
            Debug.Log( collider1 );
        }
        if ( gameObject.TryGetComponentInChildren<BoxCollider>( out var collider2 ) )
        {
            Debug.Log( collider2 );
        }
    }
}

関連記事