ソースコード
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 );
}
}
}
関連記事