コガネブログ

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

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

ソースコード

using UnityEngine;

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

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

使用例

通常

using UnityEngine;

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

拡張メソッド

using UnityEngine;

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

関連記事