How to destroy gameobject in hierarchy with a bool list.

Here I have a foreach function that outputs all the gameobject with the “enemy” tag in the hierarchy. Each “enemy” tag gameobject has a static bool candestory. How do I destroy those gameobjects in hierarchy when the bool is true?

foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject)))
{

            if(obj.CompareTag("enemy")){

                Debug.Log(obj.name);

                list1.Add(obj);
       }

public class Enemy : Character
{

public static bool shoulddestroy= false;

void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.CompareTag("Player")){
        shoulddestroy = true;
        print("you should destory on next load"+ other.gameObject);
    }
        
}

void OnTriggerExit2D(Collider2D other)
{
    if (other.gameObject.CompareTag("Player")){
        
        print("im out"+ other.gameObject);
    }
        
}

You shouldn’t use public static bool shoulddestroy if there are multiple enemies, since this will cause all instances of the script to share the value, leave off the static. As far as destroying the object you can just add:

if(shoulddestroy)
{
    int index = 0;
    foreach(GameObject obj in list1)
    {
        if(obj == gameObject) break;
        else index++;
    }
    list1.RemoveAt(index);
    Destroy(gameObject);
}  

to your Update() of the Enemy script. This will destroy the object and remove it from the list.

You can try something like this:

     if (other.gameObject.CompareTag("Player")){
         shoulddestroy = true;
         for (var i = 0; i < list1.Length; i++) {
                Destroy(list1*);*

}
print(“you should destory on next load”+ other.gameObject);
}