Count how many parents in Hierarchy?

Instead of using the inspector to add how many parents and children I have I would like to use the count method.

  1. Count how many Parents the Hierachy has, omitting Camera.

  2. How many Children does Parent “0” have. (Parent 0 would be 0-Star System)

  3. How many Children does child 7 have in folder called “Satellites”. (Would be the Satellites of Saturn for example)

I would like to use this;

parentScriptName = Hierachy.Split( '-' )[ 0 ]  // This would be the name for the script, like "0"
parentUserName   = Hierachy.Split( '-' )[ 1 ]  // This would be the name for the GUI-User Info, like "Sun"

So I only get the number as name, anything after that is only for user info.

So when everything is set then I can start find objects like for example;

GameObject.Find(parent0/child7); // Found the planet named Saturn

or

GameObject.Find(parent0/child7/Satellites/child3); // Found the Satellite named "Thethys

Count is important, If I know there are Star Systems number 0,1,2,3 and Star Systems 3 has 6 planets then I can find object 3 + 6 so I can set the transform etc.

16013-hierachy.png

If you want to traverse the Transform-hierarchy, then you need to use Transform.Find. You cannot search by partial names, so you will either need to rename yourGameObjectsto only numbers or iterate through all children using Transform.GetChild.Transformalso implements IEnumerable, so a foreach loop will work as well.

So, you remove all names and only keep the numbers. When all is done, you could use

GameObject.Find("0-Star System").transform.Find("3/6").gameObject;

Though be wary of GameObject.Find, it’s not the most performant function available…

The easiest way I can think of to count how many star systems you have, is to have an empty GameObject at (0,0,0), call it “The Center of the Universe” maybe. Then have all the Star Systems as children of that. Finding the count then is as simple as

GameObject.Find("The Center of the Universe").transform.childCount

Especially after having read your previous question, my gut feeling tells me there’s a simpler way to model the universe.

Hey thx, I was trying out the transform.count seems to work. I tried to implement the code got an error. There is a way to fix it but not sure how.
Not all planets have Satellite folder so the count result would be null, and this null spits out an error. Is there any way to turn the null into a integer 0? It is the red null refernce exception error. Another question is, is the count already an integer? Thx David.