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
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);
}
}
}
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.
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);
}
}