23

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 :-)

Mansa
  • 2,277
  • 10
  • 37
  • 67

3 Answers3

38

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);
gnerkus
  • 11,357
  • 6
  • 47
  • 71
dabadaba
  • 9,064
  • 21
  • 85
  • 155
26

There is a dedicated method:

transform.SetAsFirstSibling();
Daniel
  • 629
  • 6
  • 17
0

I know that it has been a long time since the question was asked and others have written the correct answer to solve the problem:

messageObj.transform.SetSiblingIndex(0);

But in your code, no need to scale up the child object to (1,1,1). change your code to this:

GameObject messageObj = Instantiate(storyPrefab, wallGrid.transform);
messageObj.name = "Story";

When you set the parent as the second argument in Instantiate method its set the parent to instantiated GameObject and there is no need to scale up it.