我有一个 Health 类,它有方法 TakeDamage() 和 Die()。我的 Enemy 类有一个 Health 组件,所以当我的 Enemy 受到伤害时 Health.TakeDamage() 正在执行。我如何去覆盖 Die() 方法以对不同类型的敌人进行不同的工作。
创建一个基类
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
类本身被实例化,您可能希望保留它以确保只有继承类型的组件可能存在。
现在你可以创建不同的实现,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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句