How Do I Destroy All Objects At a Given Location?
I want to destroy all objects at a particular location. The way I am currently doing it is:
void DestroyObjectAtLocation(float nX, float nY, float nZ) {
foreach (string strTag in UnityEditorInternal.InternalEditorUtility.tags)
{
GameObject[] tiles = GameObject.FindGameObjectsWithTag (strTag);
foreach (GameObject tile in tiles)
if ((tile.transform.position.z == nZ) && (tile.transform.position.x == nX) && (tile.transform.position.y == nY))
Destroy (tile);
}
}
This works perfectly but seems extremely inefficient. Is there a better way? I am largely a novice so please have mercy on my poor soul .
Answer by fafase · Nov 23, 2015 at 08:23 PM
Use a trigger sphere or box. Place it at the position, make it as large as needed and use:
void OnTriggerEnter(Collider col){
if(col.collider.gameObject.CompareTag(strTag)){Destroy(this.gameObject);}
}
Add this to the tiles and mark the collider as trigger.
I don't quite follow you. Could you make it a little more step by step? (Novice, sorry.)
Answer by wfefrfe · Nov 25, 2015 at 03:16 PM
void DestroyObjectAtLocation(float nX, float nY, float nZ, float minDist) {
Vector3 tmpLocation = new Vector3 (nX, nY, nZ);
Transform[] tiles = GameObject.FindObjectsOfType<Transform> ();
for (int i = 0; i < tiles.Length; i++) {
if(Vector3.Distance(tiles[i].position, tmpLocation) <= minDist){
Destroy(tiles[i].gameObject);
}
}
}
That works like a champ and is also a lot more adaptable; I can use it to eli$$anonymous$$ate whole areas if needed. Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220612050124im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Grabbing Object Trouble 0 Answers
Making objects with the same tag destroy eachother 1 Answer
transform position don't work with scaled parent 0 Answers
How to find the position 1 distance away from, and pointing to another object? 0 Answers
Main Camera automatically increment by 0.75 on Y axis 0 Answers