- Home /
How can I destroy GameObjects on the screen with the same name?
I've got a prefab called "GoodBall" and there is a method what creates these gameobjects. Iwould like to destroy them with a method. So if I play on the inspector it looks like : GoodBall(Clone). How can I destroy them?
Try
GameObject object = GameObject.Find("GoodBall(Clone)"); Destroy(object);
Answer by fsdjfsdkjfsdk · Jul 03, 2015 at 07:36 AM
I would suggest using tags. Tags are a way to group similar game objects into one group. It you put a tag titled "ball" on the prefab, when it is created in the scene it will remain with that tag. You can then destroy them all using:
gameObjects = GameObject.FindGameObjectsWithTag ("ball");
for(var i = 0 ; i < gameObjects.length ; i ++){
Destroy(gameObjects[i]);
}
IMPORTANT here is what tagging is if you are unfamiliar with this concept. https://www.youtube.com/watch?v=EA54-vfLkUI
Thanks! Yeah, I know about tagging and I used it but I wanted to a List insted of a simple array. This is how I made it and now it works:
public void DestroyBallsOnScreen(){
ballsOnScreen = GameObject.FindGameObjectsWithTag("Good");
ballsOnScreen = GameObject.FindGameObjectsWithTag("Bad");
print (ballsOnScreen.Length.ToString ());
for(int i = 0; i < ballsOnScreen.Length; i++){
Destroy(ballsOnScreen[i]);
}
}
Answer by terencetan · Jul 03, 2015 at 07:36 AM
You're best bet is still on instantiation to keep an array index of these objects and Destroy those objects.
Answer by starikcetin · Jul 03, 2015 at 01:06 AM
When instantiating, you can also make a referance to instantiated GameObject which can be used later on script. Like this (Three dots means you can fill there with whatever you want, as long as it's an instantiatable object.):
GameObject go = Instantiate(...) as GameObject;
Then, you can use "go" referance to destroy the object:
Destroy(go);
Best wishes.
Thanks, but it's not working. Here is my code:
public void Drop()
{
if (gameIsPlaying) {
GameObject go = Instantiate (balls [Random.Range (0, balls.Length)], this.transform.position, Quaternion.identity) as GameObject;
ballsOnScreen.Add(go);
Invoke ("Drop", Random.Range ($$anonymous$$Time, maxTime));
} else {
}
}
public void DestroyBallsOnScreen(){
print (ballsOnScreen.Count.ToString());
foreach (GameObject ball in ballsOnScreen) {
Destroy(ball);
}
}
No matter how many balls are on the screen the size of the List is 0. And I don't know why...
@GabeGabe so, they are instantiated but you list has 0 count, right?
Yes. I saw 2 or 3 balls on the screen but the count is 0.
Now I solved. This is how:
public void DestroyBallsOnScreen(){
ballsOnScreen = GameObject.FindGameObjectsWithTag("Good");
ballsOnScreen = GameObject.FindGameObjectsWithTag("Bad");
print (ballsOnScreen.Length.ToString ());
for(int i = 0; i < ballsOnScreen.Length; i++){
Destroy(ballsOnScreen[i]);
}
}