- Home /
Instantiate prefab at specific path
With the following code, I initiate a prefab inside the Content parent. However, the prefab is always loaded at the bottom of Content. Is it possibe to initiate the prefab directly under the first "singleOpretContainer"?
You will see the instantiated object (SingleOpretContainer(clone)) is at the bottom, which is incorrect.
// instantiate prefab
vContent = GameObject.FindGameObjectWithTag("scrollSingle");
Instantiate(prefab, vContent.transform,false);
Answer by MacDx · Sep 09, 2017 at 10:38 PM
You can use the SetSiblingIndex method of the transform.
https://docs.unity3d.com/ScriptReference/Transform.SetSiblingIndex.html
What you should do is save your prefab on a variable and then call the SetSiblingIndex method to change its position in the hierarchy. Like this:
//Assuming that you are instantiating the prefab as a game object
GameObject clone = Instantiate(prefab,vContent.transform,false);
clone.transform.SetSiblingIndex(1);
I can't believe it was that simple! Thanks a lot, $$anonymous$$acDx. I just tested it and it works perfectly! :)
Your answer
Follow this Question
Related Questions
How to not instantiate an object if there is another object there? 1 Answer
Instantiated Prefab doesn't find main camera 2 Answers
How can I check if an instantiated object collides with another instantiated object? 1 Answer
Piece of code creates unwanted GameObjects in scene 3 Answers
C# Why do I have to use .AddComponent and not "new (ClassName)"? 1 Answer