所以我开始学习 Swift,但我发现我想使用 Unity3d,因为它看起来学起来很有趣,而且对于游戏来说,它看起来是比 Xcode 更好的选择。然而,这意味着我必须学习一门新语言,所以我开始学习 C#。在我的项目中,我有 2 个类(class)。
我的第一个类是LivesDetract。这个类是一个边缘碰撞器。它接住掉落的物体,并减少生命值:
public class LivesDetract : MonoBehavior {
public int currentLives; //set to 3 in Unity
private int livesDecrementAmnt = 1;
void OnTriggerEnter2D (Collider2D other) {
currentLives = currentLives - livesDecrementAmnt;
}
}
第二个类名为 GameController。 GameController 控制游戏的流程。我最初将 LivesDetract 作为 GameController 的一部分,但出于组织目的,我认为它应该位于自己的类中。问题是当我尝试从 LivesDetract 类继承时出现以下错误:
错误: “非静态字段、方法或属性‘LivesDetract.currentLives’需要对象引用”
public class GameController : MonoBehavior {
IEnumeratorSpawn () {
while(LivesDetract.currentLives > 0) { // This line is where the error occurs
//Game Actions Occur
}
}
}
我认为我已经提供了足够的信息,但如果需要更多信息,请告诉我。 在 Swift 中,我能够将函数设置为变量:
var livesDetract = LivesDetract()
然后我可以使用:
while livesDetract.currentLives > 0 {
}
但这似乎在 C# 中不起作用。
最佳答案
您正尝试在不实例化对象的情况下访问 currentLives。在使用它之前,您需要在Unity中找到该对象。
关于c# - 如何在 Unity3d MonoDevelop 中使用继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36800527/