- Home /
Question by
JasonB · Aug 24, 2014 at 05:24 AM ·
c#parentchildinheritance
How can I listen for a function being called from a parent class?
Just for simplicity of getting my question across, let's say I have this:
public class Humanoid : MonoBehavior
{
void Die()
{
//Do stuff
}
}
If I have a child class, how can I accomplish a "listen" for the Die() function, like if I want something specific to happen to the child on Die() that does not happen to the parent, like this:
public class Orc : Humanoid
{
void OnDie()
{
//Do stuff unique to orcs whenever the parent class calls its Die() function
}
}
How can I accomplish this? Thanks.
Comment
If my answer works for your use case, please accept it as the correct answer, otherwise please add more information. Others can learn from your question at any point in the future, and it's most helpful when there is an accepted answer. Thanks.
Answer by iwaldrop · Aug 24, 2014 at 06:59 AM
It's quite simple, actually. Use the virtual keyword on the base class, and the override keyword on the derived class.
public class Humanoid : MonoBehavior
{
protected virtual void Die()
{
//Do stuff
}
}
public class Orc : Humanoid
{
protected override void Die()
{
// do stuff here if you want it done before the stuff in the base class
base.Die();
// do stuff here if you want it done after the stuff in the base class
}
}