- Home /
finding and destroying specific children
I've tried :
var Shadows = GetComponentsInChildren(Projector);
for (s in Shadows) Destroy(s.gameObject);
but it seems to destroy more than just the child, and the whole game seems to go nuts.
then I've tried :
var Shadows = GetComponentsInChildren(Projector);
for (s in Shadows) Destroy(s);
which works, but ofcourse it only destroys the component, which leaves me with some transform-objects (which is memory leak)
then I tried:
for (var child:Transform in transform)
{
if (child.name == "shadowcast")
{
Destroy(child);//.gameObject);
}
}
but that makes it crash as soon as it finds something with that name (infinite loop it seems)
what am I doing wrong ?
EDIT: now I've tried this:
var todelete : Array = new Array(); for (var child:Transform in transform) { if (child.name == "shadowcast") { print("destroyed shadow: "+child); //Destroy(child); todelete.Push(child.gameObject); } }
for (var s in todelete) Destroy(s);
This in case destroying the child causes the for loop to be corrupted.
and now I get "MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it." which refers to other children of the parent of these projectors. So it clearly deleted too much and lots of problems along with it. (on a side note: what I'm deleting is something (a projector) I don't acces at all in any of my scripts)
Answer by Mike 3 · Dec 27, 2010 at 03:41 PM
The first one finds projectors that are on the current gameobject, not just the children. You could do if (s.gameObject != gameObject) Destroy(s.gameObject);
The last one isn't destroying immediately, you'd need to use DestroyImmediate instead of Destroy for that to work
for the first: the parent doesn't have a projector, so that shouldn't be a problem. last one: even if it doesn't destroy immediately "for (var child:Transform in transform)" should still only get to each child once. (I'm not using find("shadowcast") for exactly that reason)
Oh, sorry, misread the latter one. Destroy(child) in that case will try destroy the transform, which shouldn't do anything at all. Not sure why it'd crash, but it needs to be Destroy(child.gameObject) in any case
it seems as though destroying child.gameObject causes the parent to be destroyed as well. I really don't get why it's like this :S
Are you absoloutely sure it destroys the parent? Have you checked the parent vanishes in the inspector?
Your answer
Follow this Question
Related Questions
delete parent or send message to parent? 2 Answers
Destroy specific child object 1 Answer
how do you delete variables or arrays? 3 Answers
How to destroy GameObject when clicked on. 2 Answers
Detect when GameObject has been deleted / removed from scene 10 Answers