Is there a way to Destroy a GameObject with given Coordinates?
Hi everyone,
I need to destroy a GameObject I've instantiated from a prefab. But I can't use "tag" to destroy it since it's tag is being used by other objects too. For example;
Think about 2 cubes side by side, I shoot 1 of them and it gets destroyed. There is no problem till this point. I can destroy the first object with "OnCollisionEnter" check. But the second object is the problem, because I want to destroy it at the same time the 1st one destroyed. The only unique thing I have about the second object is it's Vector3 coordinates.
Any help would be appreciated. Thanks in advance.
Have a good day.
Is there a reason you're not just keeping track of that cube's transform via reference? How do you already know there's a cube beside the one you're destroying?
I've created the cubes so I now they are there. And what do you mean by keeping track via reference. I'm new to Unity so it would be great if you were a little more specific, Thanks.
Answer by TreyH · Mar 16, 2016 at 11:58 AM
I think I see what you're going for? You can use OverlapSpheres http://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html.
// Destroy an object at a location
void DestroyAtPosition (Vector3 location)
{
// Pick some small search radius for your own unique situation
float radius = 0.1f;
// To guarantee results, you'll want to assign a unique Layer for the
// cubes, and then do this with that layermask as a parameter
// Get the cube sitting at our location
Collider[] hitColliders = Physics.OverlapSphere (location, radius);
// You can use a for loop more easily, but this will follow with
// the given unity example api
int i = 0;
// Destroy everything in this list
while (i < hitColliders.Length) {
Destroy (hitColliders [i].gameObject);
i++;
}
}
I think this might work, Thanks for your help marked as answer.
Answer by Ali-hatem · Mar 16, 2016 at 11:45 AM
Destroy (GameObject.FindWithTag("cubes "));
Like I said I can't use tag because it's tag is being used by other objects too. So I don't want to destroy the other objects I just want to destroy these two.
i thought you want to destroy allBut the second object is the problem, because I want to destroy it at the same time the 1st one destroyed.
Sure but there are other objects with the same tag which I don't want to destroy , I should've wrote that my bad :)