- Home /
Remove all objects that a certain type
At the moment using this, #pragma strict
function OnMouseDown() { //Turns off yellow var yellow = GameObject.Find("Yellow(Clone)"); while (yellow != null) { yellow.SetActive(true); yellow = GameObject.Find("Yellow(Clone)"); }
Debug.Log("Took off yellow");
//Turns on green var green = GameObject.Find("GreenSwitch(Clone)"); while (green != null) { green.SetActive(false); green = GameObject.Find("GreenSwitch(Clone)"); }
}
But this is highly unefficient because when an object is turned on that needs to be activated, the game freezes.
Any other ideas?
Answer by kingcoyote · Sep 03, 2015 at 07:47 PM
You've created an infinite loop here:
while (yellow != null) {
yellow.SetActive(true);
yellow = GameObject.Find("Yellow(Clone)");
}
If there is any active game object called "Yellow(Clone)", this loop will never exit, because yellow will never be null.
Is your objective to loop through all objects called "Yellow(Clone)"? Because GameObject.Find only finds the first instance, not all instances, and it doesn't return anything enumerable.
Your best bet is probably to tag all of the Yellow(Clone) objects with a specific tag and use GameObject.FindGameObjectsWithTag() to get a list of all of them.
Answer by willparsons · Sep 03, 2015 at 08:09 PM
Don't use while. Use if.
function OnMouseDown()
{
if(yellow != null && green != null)
yellow.SetActive(!yellow.activeInHierachy);
green.SetActive(!yellow.activeInHierachy);
}
That will set the yellow to the opposite of it's current active state, then set green opposite to that, so they will always be opposite.
Your answer
![](https://koobas.hobune.stream/wayback/20220612002520im_/https://answers.unity.com/themes/thub/images/avi.jpg)