- Home /
destroying children also destroys parent itself
Hi! I want to destroy gameObject children, but gameObject dont.
First i tried:
var children = player.GetComponentsInChildren(Transform);
for (var c in children)
{
Destroy(c.gameObject);
}
Destroyed children as i wanted, but with a little bonus - it also destroyed the parent that I dont want
Second approach:
var children = player.GetComponentsInChildren(Transform);
for (var c in children)
{
if(c.gameObject&&c.gameObject!=player) Destroy(c.gameObject);
}
Doesnt destroy anything at all - weird.
Third approach:
var children = player.GetComponentsInChildren(Transform);
for (var c in children)
{
if(c.gameObject&&!c.gameObject.CompareTag("Player")) Destroy(c.gameObject);
}
The same as third approach.
Can someone point what im doing wrong?
Maybe i am too tired and cant see the problem.
Answer by sven1994 · Aug 24, 2011 at 08:58 PM
Or maybe:
public void RemoveChildren(Transform parent)
{
foreach(Transform child in parent)
GameObject.Destroy(child.gameObject);
}
(C#)
You cant destroy a transform, you need to use the GameObject.
Answer by BerggreenDK · Aug 24, 2011 at 08:55 PM
I do like this when removing objects:
public void RemoveAll(string parentName)
{
// find parent object
GameObject goParent = GameObject.Find(parentName);
foreach(Transform child in goParent.transform)
{
GameObject.Destroy(child.gameObject);
}
}
Its C# but I think you should be able to translate it to Javascript without problems.
no problem - ive got expierience in both languages. Thanks for answer!
checked the marked answer, and found an error, so I ajusted my own code to be correct.
Answer by yuriythebest · May 02, 2012 at 04:35 PM
Here is my revised static version
public static void DestroyChildren(Transform someTransform)
{
foreach(Transform child in someTransform)
GameObject.Destroy(child.gameObject);
}
Answer by yuriythebest · May 02, 2012 at 04:35 PM
here is my revised static version:
public static void DestroyChildren(Transform someTransform)
{
foreach(Transform child in someTransform)
GameObject.Destroy(child.gameObject);
}