如何解决在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>();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。