I can’t get my head around this, I have a game empty called TextHolder. At times, this TextHolder is populated with text objects (via Instantiate), as children. I want to be able to get all the children (text objects) of the TextHolder and Destroy them when needed.
I don’t want to cache them, as in adding them to an array whilst I Instantiate them, I want to be able to search the TextHolder object for any children, and Destroy them:
var allChildren = TextHolder.GetComponentsInChildren(Transform);
for (var ac = 0; ac < allChildren.length; ac ++){ //var child : Transform in allChildren
print("Removing old text modules");
Destroy(allChildren[ac].gameObject);
}
Although this doesn’t actually do anything, its as if the TextHolder has no children.
Hmm. Your code is too complex. I even don’t know what it is intended to do. But maybe you should try transform instead of Transform
Here is more compact working code.
foreach (Transform child in TextHolder.transform) {
GameObject.Destroy(child.gameObject);
}
If TextHolder is an instance of an object, not class. If you want to simply remove all children of current object you can write
foreach (Transform child in transform) {
GameObject.Destroy(child.gameObject);
}
or you can write extension method for Transform class and call it on objects transform you want to clear
public static class TransformEx {
public static Transform Clear(this Transform transform)
{
foreach (Transform child in transform) {
GameObject.Destroy(child.gameObject);
}
return transform;
}
}
So you create a tag just to delete your Objects like I did. But, like @frogsbo said it: work perfectly. Just don’t forget to add = at i>0 just like @Thompsan mentioned.
int numChildren = clone.transform.childCount;
for( int i=numChildren-1 ; i>=0 ; i-- )
{
GameObject.DestroyImmediate( clone.transform.GetChild( i ).gameObject );
}
Because my objects are loaded via a Coroutine, the above examples as well as the typical approach of getting all GameObjects with a tag (using FindGameObjectsWithTag), iterating over them and removing them, I used the following approach:
public IEnumerator DoDeleteAll()
{
while (Holder.transform.childCount > 0)
{
var items = GameObject.FindGameObjectsWithTag("YOUR_TAG");
foreach (var item in items)
{
Destroy(item );
}
yield return new WaitForSeconds(0.001f);
}
}
For posterity I wanted to add here what worked for me:
var children = new List<GameObject>();
foreach (Transform child in transform) children.Add(child.gameObject);
children.ForEach(child => Destroy(child));