Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity add child to children, but at top

I am trying to add a child object to a collection of children, but I want to make sure the the latest will be the first.

Here is what I am trying to do:

GameObject
- (My new object here)
- GameObject
- GameObject
- GameObject

Here is the code I am using to instantiate my prefab:

GameObject messageObj = Instantiate(storyPrefab) as GameObject;
messageObj.name = "Story";
messageObj.transform.parent = wallGrid.transform;
messageObj.transform.localScale = new Vector3(1,1,1);

Hope this makes sense.

Any help is apreciated and thanks in advance :-)

like image 652
Mansa Avatar asked Mar 19 '16 20:03

Mansa


People also ask

How do you add children in Unity?

The simplest method of creating a child is to use Unity's hierarchy on the left side of the screen. Click on a GameObject and drag it to another GameObject.

How do I add a child to prefab Unity?

If you want to add a gameObject (which is currently inside the hierarchy) to a prefab as its (prefab's) child then you need to drag the prefab into the scene (which will also appear in the hierarchy) and then drag that gameObject into the prefab(which is inside the scene/hierarchy) ie. make a child.


2 Answers

You can change the order in the hierarchy using Transform.SetSiblingIndex.

So basically you'd want to set the first index to your desired element:

messageObj.transform.SetSiblingIndex(0);
like image 101
dabadaba Avatar answered Oct 15 '22 19:10

dabadaba


There is a dedicated method:

transform.SetAsFirstSibling();
like image 35
Daniel Avatar answered Oct 15 '22 19:10

Daniel