ソースコード
using UnityEngine; public static class GameObjectExtensions { /// <summary> /// インターフェイスを指定してコンポーネントを取得します /// </summary> public static T GetInterfaceOfComponent<T>( this GameObject self ) where T : class { foreach ( var n in self.GetComponents<Component>() ) { var component = n as T; if ( component != null ) { return component; } } return null; } }
使い方
interface ICharacter { } public class Character : MonoBehaviour, ICharacter { }
var character = gameObject.GetInterfaceOfComponent<ICharacter>();