以下の内容はhttps://baba-s.hatenablog.com/entry/2019/11/28/140000より取得しました。


【Unity】TryGetComponent を Unity 2018 でも使用できるようにする拡張メソッド

ソースコード

using UnityEngine;

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

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

使用例

using UnityEngine;

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

関連記事




以上の内容はhttps://baba-s.hatenablog.com/entry/2019/11/28/140000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14