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;
}
返回副本;
}