- Home /
How can I instantiate parented ui objects above previously instantiated children?
Or how to instantiate an Object at the top of a list (hierarchy)
I've already figured this out, so I'm going to answer it myself, but because I had so much trouble finding the answer, I'm creating a new question in the hope that other people might more easily find the answer.
This is a companion question to http://answers.unity3d.com/questions/1315548/how-to-instantiate-ui-objects-in-reverse.html
I was trying to instantiate some UI objects above previously instantiated UI objects, and was having difficulty.
Answer by Fragmental · Feb 20, 2017 at 06:05 AM
Basically, the order of UI objects is controlled by the Hierarchy. I'm guessing the order of objects in Unity terms is called the "Sibling Index". That is, all of the children of a game object are assigned a Sibling Index number starting at the top, at 0. To change their order, the key lies in some sparsely documented functions for Transform: Transform.GetSiblingIndex() which gets the order of the child in the hierarchy. Transform.SetSiblingIndex() which changes the order of the child in the hierarchy. Transform.SetAsLastSibling() which moves the child to the bottom of the hierarchy Transform.SetAsFirstSibling() which moves the child to the top of the hierarchy.
Any time you move a child above other children, the other children will move down in the index/hierarchy/list.
So since what I wanted to do was to add new instances to the top, I only needed to use
newInstance.transform.SetAsFirstSibling();
or
newinstance.transform.SetSiblingIndex(0);