我有以下方法:
protected T AttachComponent<T>(){
T gsComponent = gameObject.GetComponent<T>();
if(gsComponent == null){
gsComponent = gameObject.AddComponent<T>();
}
return gsComponent;
}
在 AddComponent
行我收到以下错误:
The type 'T' cannot be used as type parameter 'T' in the generic type or method 'GameObject.AddComponent()'. There is no boxing conversion or type parameter conversion from 'T' to 'UnityEngine.Component'.
我不确定我能做些什么来修复这个错误,为什么我不能这样做?
最佳答案
问题是 AddObject方法返回 Component .您需要告诉编译器您的 T 实际上是一种 Component。
将通用约束附加到您的方法,以确保您的 T
是 Component
protected void AttachComponent<T>() where T : Component
{
// Your code.
}
关于c# - 类型 'T' 不能用作泛型类型或方法中的类型参数 'T',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36137551/