在Unity中将值从子类更新为父类

问题描述

我试图为不同的敌人制造不同的生命值,我想通过从父类调用一个函数来更改子类的值。因此,通过这种方式,我可以简单地使用父类函数,但是对于不同类型的敌人,HP会有所不同。我是Unity新手,所以不确定如何做到这一点。

这是我的代码

Enemy.cs(父母)

public class Enemy : MonoBehavIoUr
{
    public int hp = 30;  // Need to get this value from Child class
    protected Animator anm;
    protected Rigidbody2D rb;

    protected virtual void Start() {
        anm = GetComponent<Animator>();
        rb = GetComponent<Rigidbody2D>();
    }

    public void Hurt() {
        rb.veLocity = Vector2.zero;
        anm.SetTrigger("hurt");
        hp -= 10;
        if (hp <= 0)
        {
            Death();
        }
    }

    public void Death() {
        anm.SetTrigger("death");
    }
}

Guard.cs(儿童)

public class Guard : Enemy
{
    public int hp = 50;
    protected Animator anm;
    protected Rigidbody2D rb;

    protected override void Start()
    {
        base.Start();
        coll = GetComponent<Collider2D>();
    }
}

如何为Unity中的不同敌人设置不同的hp值?

解决方法

从基类到派生类,请勿hide hp(以及其他字段/属性)。

它们已经在父类中,因此出现在派生类中

Start()中,您可以添加hp = 50;

Enemy.cs(父母)

public class Enemy : MonoBehaviour
{
    public int hp = 30;  // Need to get this value from Child class
    protected Animator anm;
    protected Rigidbody2D rb;

    protected virtual void Start() {
        anm = GetComponent<Animator>();
        rb = GetComponent<Rigidbody2D>();
    }

    public void Hurt() {
        rb.velocity = Vector2.zero;
        anm.SetTrigger("hurt");
        hp -= 10;
        if (hp <= 0)
        {
            Death();
        }
    }

    public void Death() {
        anm.SetTrigger("death");
    }
}

Guard.cs(儿童)

public class Guard : Enemy
{
    // remove the fields/properties already present in Enemy

    protected override void Start()
    {
        base.Start();
        hp = 50; // <-------------------       Set the value for Guard here
        coll = GetComponent<Collider2D>();
    }
}