我正在使用C#编写Unity3d游戏,我们有很多情况需要访问GameObject
的特定成员(如int health
)。我们这样做是使用代码,如:使用接口作为通用方法的类型参数
GameObject obj;
if(obj.GetComponent<Player>() != null) {
obj.GetComponent<Player>().health--;
}
else if(obj.GetComponent<Robot>() != null) {
obj.GetComponent<Robot>().health--;
}
// more painful code
我想要做的是所有这些类实现一个接口一样IHealth
,然后做obj.GetComponent<IHealth>().health--;
。这可能吗?我环顾四周,似乎我不能使用接口作为类型参数。
工作正常。你试过了吗? – SLaks
@SLaks否,接口只能有方法或属性,而不能有字段。 – Servy
您可能需要考虑捕获您在if块中使用的结果,以免每个对象类型都调用两次GetComponent。 –