V
V
vova_202018-07-02 22:04:12
Unity
vova_20, 2018-07-02 22:04:12

How to handle damage to objects with a bomb that are in the radius of its explosion?

Good afternoon! I’ve been sitting for the second day and I can’t understand why my code doesn’t work as it should:

void Update()
    {
        StartCoroutine(DamageObjects());
    }
    
    IEnumerator DamageObjects()
    {
        Collider2D[] collider2D = Physics2D.OverlapCircleAll(transform.position, explosionRadius);

        foreach (Collider2D col in collider2D)
        {
            if (col.tag == enemyName)
            {
                yield return new WaitForSeconds(0.3f);
                DamageEnemy(col.transform);
                Destroy(gameObject);
            }
        }
    }
    
    void DamageEnemy(Transform enemy)
    {
        Enemy e = enemy.GetComponent<Enemy>();

        if (e != null)
        {
            e.TakeDamage(damage);
        }
    }

When the bomb explodes and objects that have entered the radius of the explosion, then only one object is damaged. This code used to work. Who will tell you how to make sure that damage is done to all objects that have entered the explosion radius?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vova_20, 2018-07-03
@vova_20

Thanks everyone for your help!!! I solved the problem :) If anyone is interested and needs it, then see:

void Update()
    {
        ...
        transform.position = nextPos;

        if (nextPos == endPoint)
        {
            DamageObjects();
        }   
    }

    void DamageObjects()
    {
        Collider2D[] collider2D = Physics2D.OverlapCircleAll(transform.position, explosionRadius);
        if (collider2D.Length > 0)
        {
            foreach (Collider2D col in collider2D)
            {
                if (col.tag == enemyName)
                {
                    DamageEnemy(col.transform);
                    Destroy(gameObject);
                }
            }
        }
        else
        {
            Destroy(gameObject);
        }
        
    }

    void DamageEnemy(Transform enemy)
    {
        Enemy e = enemy.GetComponent<Enemy>();

        if (e != null)
        {
            e.TakeDamage(damage);
        }
    }

C
ColdSpirit, 2018-07-03
@ColdSpirit

Put Destroy(gameObject);after the loop foreach:

// проходим по каждому задетому коллайдеру
foreach (Collider2D col in collider2D)
{
  // если это враг
  if (col.tag == enemyName)
  {
    // ждем 0,3с
    yield return new WaitForSeconds(0.3f);
    // наносим ему урон
    DamageEnemy(col.transform);
  }
}

// уничтожаем бомбу
Destroy(gameObject);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question