Unity list of GameObjects

If youve ever wanted to get all of the children attached to a Unity GameObject and turn them into an array, there is a simple way to do it. I did this a number of times with my game Puzzledorf, for example with the UI, getting all of the buttons that were children of a menu.

The following code gets the jobs done in C#.

Transform[] allChildren = GetComponentsInChildren[]; foreach [Transform child in allChildren] { child.gameObject.SetActive[false]; }

Since each child has a Transformcomponent, this code will get all of the children and convert them into an array of Transforms. It will then loop through the array and deactivate them all. Read more about foreach loops here.

Although its an array of transforms, you can see from the loop its easy to access the GameObject. If you wanted a list of GameObjects rather than Transforms, you could improve the code thus:

Transform[] allChildren = GetComponentsInChildren[]; List childObjects = new List[]; foreach [Transform child in allChildren] { childObjects.Add[child.gameObject]; }

If you enjoyed reading, try my game Puzzledorf out on Steam and Humble Bundle.

Share this:

Related

  • How To Get Game Objects With A Specific Script Attached Unity C#
  • August 7, 2017
  • In "C# Unity"
  • How To Change Sprites Colour Or Transparency Unity C#
  • February 19, 2019
  • In "C# Unity"
  • How To Do 2D Top-Down Movement Unity C#
  • June 24, 2018
  • In "C# Unity"
Categories: C# Unity, Tutorials, Unity
Tags: C++, programming, Programming Tutorials, Unity
Leave a Comment

Stuart's Pixel Games

Back to top

Video liên quan

Chủ Đề