Change coordinates of children and grandchildren of gameobject in panel

Hello everyone. I have an object which has too many children, grandchildren and children of grandchildren (both more than 1000 objects). Example structure of hierarchy for that gameobject:

-Object1

-----Object2

---------Object3

---------Object4

-----Object5

---------Object6

---------Object7

-------------Object8

-----Object9 …

Also I have an UI panel and I create empty GameObject for each object in that panel at runtime. I could do that with “for” loop and set them using AddComponent and GetComponent for making them “Text”. For coordinate of objects I used;

newText.GetComponent<RectTransform> ().localPosition = new Vector3 (x, y, 0.0f);

y component increases properly, so there is no problem about that. However, each object should look like in panel just like hierarchy above. How can I set x component of coordinates of each object for that aim? I tried that;

newText.GetComponent<Text>().text = room.name;
room.name = oda.GetComponentsInChildren<Transform>()[n].gameObject.name;
if (room.GetComponentsInChildren<Transform>()[n-1].childCount > 0)
            x += 25.0f;
else if (room.GetComponentsInChildren<Transform>()[n].childCount > 0)
            x -= 25.0f;
n++;

(newText is a new GameObject which created at runtime)

room object is a root of that gameobject which I wrote it as a public GameObject in script. I can access each child and grandchild of room thanks to GetComponentsInChildren array. My simple if - else if condition works for first level children but for grandchildren and children of grandchildren it doesn’t. I used C# by the way. Thanks in advance.

It might be helpful to see more of your code; in the 2nd code piece you posted, you’re modifying the value x, but where are you using it?

NB If I understand correctly, you are trying to mirror a scene hierarchy tree view in your UI elements. Another way to do this would be to inspect the number of parents of each object, e.g.

float xOffset = 0;
Transform t = // (current transform you're looking at)
Transform t_temp = t;
while (t_temp.parent != null) {
    xOffset += 25;
    t_temp = t_temp.parent;
}
t.position = new Vector3(xOffset, y, 0);

I’m not saying that’s a better way to do it, just offering it as an alternative if it interests you.