destroy gameObjects with tag

I’m just trying to destroy all gameObjects with a certain tag if the player does something. Is there a simple way to do this? I’ve tried Destroy(GameObject.FindGameObjectsWithTag(“name”); but it throws out an error.

GameObject.FindGameObjectsWithTag(“name”) returns a an of game objects. The Destroy() function only takes one object per call. A better solution would be (in C#):

GameObject[] names = GameObjects.FindGameObjectsWithTag("name");

foreach(GameObject item in names)
{
     Destroy(item);
}

my code is in javascript. When I try to make a seperate script in C# with your code and access it in the javascript file when its time, i get an error message saying unkown identifier ‘scriptName’.

It should be easy enough to convert to js, I mean come on, it’s 3 lines of code.

var names;
function Start () {
names = GameObject.FindGameObjectsWithTag("name");
	for (var name in names)
	{
	Destroy(name);
	}
}

A JS version

1 Like

Thanks, I was able to destroy all of the gameObjects at once. However, I want to know how to change materials of multiple gameObjects. I’ve tried this code but it gives me an error saying that ‘‘texture’’ is null.

roadTextures = GameObject.FindGameObjectsWithTag("road");
  			for (var texture in roadTextures)
		    {
		    texture.Material.Color = new Color (0,0,0,1);
		    }

When you use the statement GameObject.FindGameObjectsWithTag() … what you get back in return is an array of GameObject instances. Have a look at the GameObject manual page found here:

http://unity3d.com/support/documentation/ScriptReference/GameObject.html

Note this object does NOT have a property/variable called “Material”. This means that your line #4 will fail.

I suspect that what you want to do is investigate the property called “renderer” of a GameObject which itself has a property called “materials”.

How can I Destroy(gameObject) which was pointed by RaycastHit ???

i want to know how u can able to destroy all of the game objects at once.thanks

[QUOTE="

var names;
function Start () {
names = GameObject.FindGameObjectsWithTag("name");
    for (var name in names)
    {
    Destroy(name);
    }
}

[/QUOTE]

hi … i need this, but on unity 5.x
because like this give error.

please help
thanks a lot