LoginSignup
24
19

More than 5 years have passed since last update.

GetComponentでinterfaceを使いたい場合

Last updated at Posted at 2014-01-06

特定のコンポーネントを取得したい場合、GetComponentを使うと思います。
で、その時に特定のinterfaceを実装しているものを取得したい場合の話。

例えばIHogeを実装しているコンポーネントを取得したい場合、以下のように書きたくなります。

InterfaceTest.cs
using UnityEngine;
using System.Collections;

public class InterfaceTest : MonoBehaviour
{   
    void Start ()
    {
        var hoge = GetComponent<IHoge>();   
        if (hoge != null) {
            hoge.Hoge();        
        }
    }   
}

interface IHoge
{
    void Hoge();
}

しかしGetComponent()は「where T : UnityEngine.Component」となっているようで、
以下のようなエラーが出ます。

Assets/InterfaceTest.cs(9,28): error CS0309: The type `IHoge' must be convertible to `UnityEngine.Component' in order to use it as parameter `T' in the generic type or method `UnityEngine.Component.GetComponent<T>()'

このエラーはジェネリックメソッドを使わずに、GetComponent(Type)を呼び出すと回避出来ます。

public class InterfaceTest : MonoBehaviour
{   
    void Start ()
    {
        var hoge = GetComponent(typeof(IHoge)) as IHoge;

        if (hoge != null) {
            hoge.Hoge();        
        }
    }   
}

気持ち的にはジェネリックを使いたいですが...

24
19
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
19