[Solved] Destory All GameObjects With Tag

Hi there fairly simple question from a beginner. When my player dies I wish to destroy all objects with certain tags. Below is my script when a object collides with my player the player gets destroy. After that all enemy objects stay and respawns keep respawning objects and draining memory for no reason! So just wish to destroy objects when my player gets destroyed :slight_smile:

using UnityEngine;
using System.Collections;

public class DestroyCubes : MonoBehaviour
{
    void OnCollisionEnter (Collision col)
    {
        if (col.gameObject.name == "Player") {
                        Destroy (col.gameObject);


            SpecialEffectsHelperGreen.Instance.Explosion (transform.position);
        }
    }
}
1 Like

Thanks for the reply and direction. I am not sure if this modification is correct

using UnityEngine;
using System.Collections;

public class DestroyCubes : MonoBehaviour
{
        void OnCollisionEnter (Collision col)
        {
                if (col.gameObject.name == "Player") {


                        Destroy (col.gameObject);

   
                        SpecialEffectsHelperGreen.Instance.Explosion (transform.position);

                }

        GameObject.FindGameObjectsWithTag("Enemy");

        Destroy (GameObject);



                }
        }

}

get this error

" Assets/Scripts/DestroyCubes.cs(27,1): error CS8025: Parsing error " please advise thank you.

Parsing error simply means you have an extra } at the end of your code.

There are other problems in this script

FindGameObjectsWithTag returns an array, so you have to loop through it and destroy the objects. If you check that link, in the example, they show looping through it, but they do something else, not destroy, but you’ll get the idea.

1 Like

Thank you very much for pushing me towards the right direction and I guess not spoon feeding me haha I studied the link and some unity videos on looping and came up with this and attached it to the player and works like a charm.

using UnityEngine;
using System.Collections;

public class DestroySafecube : MonoBehaviour
{

        void  OnDestroy ()
        {

                GameObject[] SafeCube;
   
                SafeCube = GameObject.FindGameObjectsWithTag ("Safecube");

                foreach (var i in SafeCube)

                        Destroy (i);
   
        }
   
   
}
1 Like

Good job.