我有有方法TakeDamage(一个卫生级)和死亡()。我的敌人类有一个健康成分,所以当我的敌人受到伤害Health.TakeDamage(正在执行)。我怎么去和覆盖模具()方法对不同类型的工作方式不同的敌人。
创建一个基类
public abstract class Health : MonoBehaviour
{
// make a member e.g. protected so it is not public but still accesible by inherited classes
protected float health = 100f;
// Now you either can make the method abstract
// This means every inheritor later HAS to implement this method
public abstract void Die();
// or you can make it virtual
// This means this class already provides an implementation
// but an inheritor could
// a) simply use it
// b) extend it or
// c) completely overrule it
public virtual void TakeDamage()
{
Debug.Log("Ouch!");
health -= 1;
}
}
注意:如果您的Health
类没有任何abstract
方法,你可能想也是从类定义本身删除abstract
关键字,使其只public class Health : MonoBehaviour
。但是,如果要严格防止基Health
类本身是在所有你可能想保持它,以确保inhertided类型的唯一部件可能存在的实例。
现在,您可以创建Health
的不同实现不改变它在所有
public class NormalHealth : Health
{
// since it is abstract we have to implement Die
public override void Die()
{
// whatever happens here
}
// But if we want to use the default TakeDamage we just do nothing
}
或覆盖默认行为
public class WeakHealth : Health
{
// Since it is abstract we have to implement Die
public override void Die()
{
// whatever happens here
}
// Now we replace the TakeDamage
public override void TakeDamage()
{
// by not calling base.TakeDamage we don't execute the base implementation at all
Debug.Log("Huge Ouch!");
health -= 10;
}
}
或代替它延伸替换它的
public class HealthWithSound : Health
{
public AudioSource someAudioSource;
public AudioClip someClip;
// Since it is abstract we have to implement Die
public override void Die()
{
// whatever happens here
}
// This time we only extend the base's TakeDamage with e.g. sound
public override void TakeDamage()
{
base.TakeDamage();
someAudioSource.PlayOneShot(someClip);
}
}