For context, I got this code from this tutorial, particularly at 2:27:28.
I have two classes, Player
and Warrior
. I want the Warrior
class to inherit from the Player
class. The Player
class looks like this:
public class Player: MonoBehaviour
{
//Variables and Properties
private string _playerName;
public string pName { get => _playerName; set => _playerName = value; }
private int _playerHealth;
public int Health { get => _playerHealth ; set => _playerHealth = value ; }
private int _playerPower;
public int Power { get => _playerPower; set => _playerPower = value ; }
//Constructors
public Player() { } //Constructor 1
public Player(string name, int health, int power) //Constructor 2
{
pName = name;
Health = health;
Power = power;
}
}
And the Warrior
class looks like this:
public class Warrior : Player
{
public Warrior(string name, int health, int power)
{
pName = name;
Health = health;
Power = power;
}
}
Whenever I remove Constructor 1 in Player
(the blank one), I get an error in the Warrior constructor. But if I remove the Warrior
Constructor itself, then I get an error when declaring the Warrior
class itself. I don't understand why it would be necessary to add Constructor 1, especially when I already have Constructor 2 in the Player
class, to begin with.
Is there something I am missing? Or does a parent class always need an extra constructor whenever the child is being declared? And if so, Why? Or maybe inheriting constructors in UNITY works differently?
I tried removing Constructor 1 and using the command CTRL + .
in VS, and even the debugger confuses me. I also tried googling online to no avail.
Like rshepp said, you probably shouldn't use constructors with MonoBehaviors. Instead, use Start() and Awake() to initialize.