【问题标题】:How can I override a component function specifically for a type on unit?如何覆盖专门针对单元类型的组件功能?
【发布时间】:2019-06-27 15:23:57
【问题描述】:

我有一个 Health 类,它具有 TakeDamage() 和 Die() 方法。我的 Enemy 类有一个 Health 组件,所以当我的 Enemy 受到伤害时, Health.TakeDamage() 正在执行。我如何去覆盖 Die() 方法以在不同类型的敌人上以不同的方式工作。

【问题讨论】:

标签: c# unity3d components


【解决方案1】:

创建一个基类

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 关键字并使其仅是 @987654325 @。但是,如果您想严格防止基类 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);
    }
}

【讨论】:

  • 重点是我的类并没有以任何方式继承 Health 类,它只是使用它的一个实例。
  • 这同样适用于非MonoBehaviour 类型的类,只是让不同的 Enemy 脚本使用不同的 Health 实现...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
  • 2012-02-18
  • 2014-05-13
相关资源
最近更新 更多