I am making a game with some animals. Each animal inherits from the class Animal. I have a rocks which the animals can collide into. When I handle the collision I detect if an Animal collided with the rock:
void OnTriggerEnter(Collider other)
{
Animal animal = other.gameObject.GetComponent<Animal> ();
if (animal != null) {
animal.onHitRock (this);
}
}
In the Animal class I have a virtual function that can be overidden:
public virtual void onHitRock(Rock rock){
Debug.Log ("onHitRock: " + this.species + " needs to override this if it reacts to rock.");
Debug.Log ("type of animal that hit the Rock: " + this.GetType ().Name);
}
Then in the Pig class which extends the Animal class:
public override void onHitRock(Rock rock){
Debug.Log ("Pig hits rock!");
}
Output:
onHitRock: Pig needs to override this if it reacts to rock.
type of animal that hit the Rock: Pig
I believe that because I call the onHitRock method on the Pig cast as an Animal it just calls the Animal.onHitRock method and not the Pig.onHitRock method.
How do I call the Pig’s overriding method, short of cycling through each individual species with GetComponent? I’d like to just call the top most casting of the script that inherits from animal without knowing what it is.
Thanks
SOLVED
I had not saved the Pig class with the override method.