我正试图从脚本敌人向脚本播放器调用此方法,有人可以指导我吗?
第一个代码命名空间是敌人,第二个是播放器
private void OnTriggerEnter2D(Collider2D other)
{
DamageDealer damageDealer = other.gameObject.GetComponent<DamageDealer>();
ProcessHit(damageDealer);
}
public void ProcessHit(DamageDealer damageDealer)
{
health -= damageDealer.GetDamage();
if (health <= 0)
{
Destroy(gameObject);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
}
答案 0 :(得分:1)
尝试使用Enemy
和Player
都通用的抽象基类,例如Character
或任何对您的程序有意义的基类。
public abstract class Character
{
public virtual void OnTriggerEnter2D(Collider2D other)
{
DamageDealer damageDealer = other.gameObject.GetComponent<DamageDealer>();
ProcessHit(damageDealer);
};
public void ProcessHit(DamageDealer damageDealer)
{
//ProcessHit accessible for all classes that inherit Character
health -= damageDealer.GetDamage();
if (health <= 0)
{
Destroy(gameObject);
}
}
}
public class Enemy : Character
{
//this has both methods as declared in Character
}
public class Player : Character
{
// this needs to be overriden for Player
public override void OnTriggerEnter2D(Collider2D other)
{
//Enter OnTriggerEnter2D logic for Player
}
}
因此,如果您希望任何具有OnTriggerEnter2D的类以不同的方式运行,只需重写它并更改逻辑即可。