I’m fairly new to Unity, so I’m not sure how things like GetComponent respond to inheritance.
The other thing that’s a bit tricky with C# is the concept of polymorphism and using the virtual and override keywords.
Let’s say you have a base class, Car, and two classes that extend Car: Honda and Toyota.
Let’s say each class has a method, Honk(), that simply outputs:
Car: “Beep! I’m a car!”
Honda: “Beep! I’m a Honda!”
Toyota: “Beep! I’m a Toyota!”
Now, the concept of polymorphism is that you’ll be able to treat both a Honda and a Toyota as a Car (because they have all of the methods and properties of a car).
That is, this is legal:
Car myCar = new Toyota();
Now, if you just override Honk() in the Toyota class as you did above, calling myCar.Honk() will actually output “Beep! I’m a car!”. What you’d probably want, though is for the Honk() function to route to the Toyota’s version of it. That is, even though the myCar variable is of type Car, you want the compiler to realize that there’s actually a Toyota in there.
To do that, you’d mark the Honk() method as virtual in the parent class Car:
public virtual void Honk()
{
Debug.Log("Beep! I'm a car!");
}
And then in the Toyota class you’d mark is as override:
public override void Honk()
{
Debug.Log("Beep! I'm a Toyota!");
}
If you leave out the override keyword, it implicitly uses the new keyword, which tells the compiler that the function only applies to variables of type Toyota (but not if you have a variable of type Car that points to a Toyota).
So if you have the Toyota Honk() as:
public new void Honk()
{
Debug.Log("Beep! I'm a Toyota!");
}
And do this:
Car myCar1 = new Toyota();
Toyota myCar2 = new Toyota();
myCar1.Honk();
myCar2.Honk();
With the virtual/override combo, you’ll get “Beep! I’m a Toyota!” for both honks. With the new keyword, or without any keywords, you’ll get:
Beep! I’m a Car!
Beep! I’m a Toyota!
Which is probably not what you want. In a game situation, it’s pretty common to have an array of Enemy objects and then call a function like Attack() on each one and let whatever subclass the objects really are handle it. You’d have to use the virtual/override keywords for this.
Hope that makes sense! It’s a little late here, and my brain is quickly fading…