As in the title, I am trying to use overlapcircleall to deal damage to all enemies exactly once, but sometimes works correctly, but sometimes the damage is applied multiple times to the same enemy, where each enemy should have been dealt damage exactly once if they are inside the explosion radius. When testing the game, i believe the higher the amount of enemies inside the explosion area, the bigger the chances of dealing damage multiple times to all enemies inside that area. I have watched some videos and tried to fix it, but nothing seems to work. I also tried using circle collider instead but i get the same problem. But overlapcircleall seems to work better at least than circlecollider.
int bazucaDamage = GameObject.Find("Bazuca").GetComponent<WeaponScript>().damage;
circleCollider = GetComponent<CircleCollider2D>();
float explosionRadius = circleCollider.radius;
int enemyLayer = 1 << 6;
int playerLayer = 1 << 3;
Collider2D[] hitCollidersEnemies = Physics2D.OverlapCircleAll(transform.position, explosionRadius, enemyLayer);
foreach (Collider2D hitCollider in hitCollidersEnemies)
{
// Try to get the Enemy component (or any script that handles taking damage)
ZombieScript enemy = hitCollider.GetComponent<ZombieScript>();
if (enemy != null)
{
// Apply damage to the enemy
enemy.TakeDamage(bazucaDamage);
}
}
Collider2D[] hitCollidersPlayer = Physics2D.OverlapCircleAll(transform.position, explosionRadius, playerLayer);
if(hitCollidersPlayer.Length > 0)
{
GameObject.Find("Player").GetComponent<PlayerScript>().TakeDamage(bazucaDamage);
}
StartCoroutine(EndExplosion());
The player also takes more damage if the enemies takes more damage than what it actually should.
1
The code you showed looks correct. Since you said that the damage is sometimes dealt multiple times to all the enemies in the range, the problem might be that sometimes this code is run multiple times instead of once. Can you show where this code is called from?
Kevin Ghossoub is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.