简体   繁体   中英

The constructor is not reading the values from an object

The constructor for my Player class is compiling, but it's not actually transferring the values of any of the fields from the Animal object. The Animal object is available, because I can use Debug.Log() to check for each of its values via an added Update() function. Are objects not capable of being accessed in a constructor?

public class Player : MonoBehaviour {

    public Animal myAnimal;

    int hpMax;
    int power;
    int defense;

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

And here is the imported Animal (a Sheep , actually, inherited from Animal ):

public class Sheep : Animal {

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

The superclass:

public abstract class Animal : MonoBehaviour {

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

You need to create object of that animal.

If You inherit from MonoBehavior You can't create it by new keyword so - In player Constructor You need to call:

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

Or second solution - don't inherit from MonoBehaviour in Your animal class and then just creat new object of that animal:

private animal myAnimal = new Sheep();

Assuming you are setting your myAnimal field in the inspector or somewhere else, you can not access it in the constructor of your Player class, as it is not set yet. Try to do that in the Awake method:

public class Player : MonoBehaviour {

    public Animal myAnimal;

    int hpMax;
    int power;
    int defense;

    void Awake() {

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

The Animal object in the Player class won't be initialised because it's not static and therefore it can't exist yet. It would be wrong to make this static anyway.

Consider passing the Animal object into the constructor - Player(Animal animal) or even have a static method on the Player class Player.CreateFromAnimal(Animal animal) which returns a new Player . Furthermore, remove the public access modifier from Animal as this is breaking encapsulation.

Have a read of encapsulation and Object Oriented Programming in general. It will help when design classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM