将组件作为模板变量传递

时间:2014-07-29 04:38:53

标签: templates unity3d

我正在尝试创建一个通用方法,它将从GameObject中删除重复的组件。

我收到以下编译错误。我该如何解决这个问题?

The type `T' must be convertible to `UnityEngine.Component' in order to use it as parameter `T' in the generic type or method

继承我的代码:

public static bool removeDuplicateComponents<T>(GameObject go) {

    bool hasComponent  = false;
    bool hasDuplicates = false;

    foreach (T c in go.GetComponents<T>()) {  // error line
        if (!hasComponent) {
            hasComponent = true;
            continue;
        }

        Destroy(c);
        hasDuplicates = true;
    }

    return hasDuplicates;
}

1 个答案:

答案 0 :(得分:1)

您可以通过在函数声明中添加where T : Component来解决此问题。

public static bool removeDuplicateComponents<T>(GameObject go) where T : Component {

    bool hasComponent  = false;
    bool hasDuplicates = false;

    foreach (T c in go.GetComponents<T>()) {  // error line
        if (!hasComponent) {
            hasComponent = true;
            continue;
        }

        Destroy(c);
        hasDuplicates = true;
    }

    return hasDuplicates;
}