December 7, 2022

162 words 1 min read

Unity GameObject Extension to Remove All Children!

Unity GameObject Extension to Remove All Children!

I want to show you a neat little trick, that utilizes the slick extension methods of C#! What If I tell you, that you can remove all of the child GameObjects of any Unity transform object with only one line of code? That would be awesome right? And let me tell you it’s not an old-school method call.

To add extension methods to C# (extend the methods of an existing closed class) you have to create a public static class. Inside the static class, you can create some methods, and if the first parameter of the method starts with a this, you can use that parameter as the instance of your method. Let me show you what I mean:

public static class MyAwesomeExtensions
{
    public static void ClearChildren(this GameObject go)
	{
		var children = new List<GameObject>();
		foreach (Transform child in go.transform) children.Add(child.gameObject);
		children.ForEach(child => GameObject.Destroy(child));
	}
}

After this, you will have a new method on the GameObject instances, called ClearChildren:

anykindOfGameObjectWithChildren.ClearChildren();