构造函数没有从对象中读取值

The constructor is not reading the values from an object

我的 Player class 的构造函数正在编译,但实际上并没有从 Animal 对象传输任何字段的值。 Animal 对象可用,因为我可以使用 Debug.Log() 通过添加的 Update() 函数检查它的每个值。对象是否不能在构造函数中访问?

public class Player : MonoBehaviour {

    public Animal myAnimal;

    int hpMax;
    int power;
    int defense;

    Player(){
        hpMax = myAnimal.hpMax;
        power = myAnimal.power;
        defense = myAnimal.defense;
        }
}

这里是导入的Animal(一个Sheep,实际上是继承自Animal):

public class Sheep : Animal {

    public Sheep(){
        hpMax = 100;
        power = 10;
        defense = 10;
}

超级class:

public abstract class Animal : MonoBehaviour {

    public int hpMax;
    public int power;
    public int defense;
}

您需要创建该动物的对象。

如果你继承自 MonoBehavior 你不能通过 new 关键字创建它 - 在播放器构造函数中你需要调用:

myAnimal = gameObject.AddComponent<Sheep>(); // You must have this gameObject somewhere

或者第二个解决方案——不要从你的动物中的 MonoBehaviour 继承 class 然后只创建该动物的新对象:

private animal myAnimal = new Sheep();

假设您在检查器或其他地方设置 myAnimal 字段,您无法在 Player class 的构造函数中访问它,因为它尚未设置.尝试在 Awake 方法中这样做:

public class Player : MonoBehaviour {

    public Animal myAnimal;

    int hpMax;
    int power;
    int defense;

    void Awake() {

        hpMax = myAnimal.hpMax;
        power = myAnimal.power;
        defense = myAnimal.defense;
    }
}

Player class 中的 Animal 对象不会被初始化,因为它不是 static,因此它还不存在。无论如何做这个static都是错误的。

考虑将 Animal 对象传递给构造函数 - Player(Animal animal) 或者甚至在 Player class Player.CreateFromAnimal(Animal animal) 上有一个静态方法,其中 returns 一个新的Player。此外,从 Animal 中删除 public 访问修饰符,因为这会破坏封装。

通读一下封装和面向对象编程。设计时会有帮助 classes.