我在从一个类到另一个类调用方法时遇到麻烦

时间:2019-09-30 06:17:15

标签: c# unity3d

我正试图从脚本敌人向脚本播放器调用此方法,有人可以指导我吗?

第一个代码命名空间是敌人,第二个是播放器

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) 
{
}

1 个答案:

答案 0 :(得分:1)

尝试使用EnemyPlayer都通用的抽象基类,例如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的类以不同的方式运行,只需重写它并更改逻辑即可。