[英]The type 'T' cannot be used as type parameter 'T' in the generic type or method
I have the following method: 我有以下方法:
protected T AttachComponent<T>(){
T gsComponent = gameObject.GetComponent<T>();
if(gsComponent == null){
gsComponent = gameObject.AddComponent<T>();
}
return gsComponent;
}
On the AddComponent
line I am getting the following error: 在AddComponent
行上,出现以下错误:
The type 'T' cannot be used as type parameter 'T' in the generic type or method 'GameObject.AddComponent()'. 类型“ T”不能用作通用类型或方法“ GameObject.AddComponent()”中的类型参数“ T”。 There is no boxing conversion or type parameter conversion from 'T' to 'UnityEngine.Component'. 没有从“ T”到“ UnityEngine.Component”的装箱转换或类型参数转换。
I am not sure what I can do to fix this error, why Can I not do this? 我不确定该如何解决此错误,为什么我不能这样做?
The issue is that the AddObject method returns a Component . 问题是AddObject方法返回一个Component 。 You need to tell the compiler that your T is actually a type of Component. 您需要告诉编译器您的T实际上是Component的一种。
Attach a generic constraint to your method, to ensure that your T
s are Component
s 将通用约束附加到您的方法,以确保T
是Component
。
protected void AttachComponent<T>() where T : Component
{
// Your code.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.