- Home /
How to destroy all enemies within a certain collider?
Hey everyone, I'm remaking a level from Mega Man 2, and when I leave a room I want all the enemies still alive in that room to be destroyed. I have a BoxCollider2D covering each room with this EnemyTracker script attached, which when the player exits this collider, every enemy is destroyed. That's the problem though, every single enemy on the map is destroyed instead of only the enemies in that room (Collider2D). Anyone know what I can do to fix this? Any help is appreciated!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// This script is to be applied to each CamBounds collider to track (and destroy) enemies that are within the collider.
/// </summary>
public class EnemyTracker : MonoBehaviour
{
private GameObject[] aliveEnemies;
private void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
DestroyAllEnemies();
}
}
void DestroyAllEnemies() // destroy all alive enemies once you leave an area (so they don't follow you)
{
aliveEnemies = GameObject.FindGameObjectsWithTag("Enemy");
for (var i = 0; i < aliveEnemies.Length; i++)
{
Destroy(aliveEnemies[i]);
}
}
}
When do you create your enemies in the first place? And did you design the rooms or do you generate them procedurally?
There are just empty game objects positioned in each room which spawn an enemy when the player gets near the spawner (and a cooldown timer to spawn again after a certain amount of time). There is only a set number of rooms, each with BoxCollider2D attached to it.
Ok when you spawn them put them in a list at the same time. And when you destroy enemies just loop through that list.
you should really have a variable assigned to each enemy when they are spawned to tell what room they are in. you should also know what room your player is in at all times.
if your items are only spawned when your player is entering a room. your player's room variable should be static. this way all the spawned enemies can grab it in there Start functions. then when the player leaves you can destroy anything without a matching room number.
Answer by Nishchhal · Apr 01, 2019 at 03:45 AM
Its better you sort them up while you spawn them. The simplest way would be to make a parent gameobject and spawn all enemies as its child. You could use names for parent gameobject like "Room_1_Enemies", so it becomes easy for you to sort them out. You can track which room the player left and check if there is any Enemy holder gameobject for that room, if yes then Destroy.