Upcasting to an unknown class

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.

Uhm. you haven’t said what behaviour you actually see. The way you structured your classes should work. And no, as long as a method is virtual and overridden in a derived class, calling the method on a baseclass reference will always call the overridden method.

Do you actually get any debug log message? If so what does it say? If you get the log from the base class, have you tried printing the class name? (this.GetType().Name).

Also are you sure there is only one “Animal” derived class on the same object? GetComponent simply returns the first “Animal” it finds on the object.

If you don’t get any debug log, make sure you look for the component on the right object. You may also want to print the object name inside your OnTriggerEnter method (other.gameObject.name) and make sure it’s the right object. If you actually see a child object you may use GetComponentInParent which looks on the object you use and goes up the hierarchy as long as no such component was found.