Reputation: 31
These clones are created by script. If I want to change the sort of them(in the hierachy), what should I do? I tried to print the pos but it turned out to be the pososition of the prefab not the clone, which means all these clones share same name and position.
Really need help.Thanks a lot.
Upvotes: 2
Views: 3084
Reputation: 2612
To get the index of a GameObject in its parent hierarchy and change its position, you can use the GetSiblingIndex and SetSiblingIndex function of the transform component of your child. The first one will give you the index corresponding to the position of a specific child in the parent's hierarchy, while the second will allow you to place it at a specific index.
The following example will for instance print the index of all the children elements, so from 0 to numberChild - 1 :
void Start()
{
Transform parentTransform = Parent.transform;
int numberChildren = parentTransform.childCount;
for(int i = 0; i < numberChildren; i++)
{
int index = parentTransform.GetChild(i).GetSiblingIndex();
Debug.Log(index);
}
}
It's up to you to decide how you will use the SetSiblingIndex function to reorder your elements for your game's purposes.
As side notes: you can change the name of a GameObject by using the name component of a GameObject. It can be quite handy if you want to identify quickly all your children:
Parent.transform.GetChild(i).name = "Item1";
Also, if you're thinking about using the transform component of your Parent object often, store the reference in your class.
Upvotes: 4