Answer the question
In order to leave comments, you need to log in
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);
}
}
Answer the question
In order to leave comments, you need to log in
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);
}
}
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 questionAsk a Question
731 491 924 answers to any question