Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Templates 将组件作为模板变量传递_Templates_Unity3d - Fatal编程技术网

Templates 将组件作为模板变量传递

Templates 将组件作为模板变量传递,templates,unity3d,Templates,Unity3d,我试图创建一个通用方法,从游戏对象中删除重复的组件 我得到以下编译错误。我怎样才能解决这个问题 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

我试图创建一个通用方法,从游戏对象中删除重复的组件

我得到以下编译错误。我怎样才能解决这个问题

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;
}
publicstaticbool-removeDuplicateComponents(gameobjectgo){
bool hasComponent=false;
bool hasDuplicates=false;
foreach(tc在go.GetComponents()中){//错误行
如果(!hasComponent){
hasComponent=true;
继续;
}
销毁(c);
hasDuplicates=true;
}
返回副本;
}

您可以通过在函数声明中添加
其中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;
}
publicstaticbool-removeDuplicateComponents(GameObject-go),其中T:Component{
bool hasComponent=false;
bool hasDuplicates=false;
foreach(tc在go.GetComponents()中){//错误行
如果(!hasComponent){
hasComponent=true;
继续;
}
销毁(c);
hasDuplicates=true;
}
返回副本;
}