- Home /
instantiate in hierarchy
Would someone please give me an script example of instantiating a game object in a "specific place in the hierarchy? In other words I would like to create(Instantiate) a game object(like a sphere) in the child position of the main camera for example) Everytime I write a script with "Instantiate" it creates the game object outside the Hierarchy. In my game the camera is moving forward constantly and I'd like to have objects appear in the cameras view and stay in the cameras view even if I move the camera. I want them to stay in a fixed position in the cameras field of view. Thanx
Answer by byerdelen · Jun 14, 2011 at 10:47 AM
The best way to use for me is instantiate and make it the objects child after, I
couldn't find a better solution that comes with instantiate function and I strongly
believe it is only way and it is efficient. Example:
Make a prefab object with the script example below,
after instantiate,
camera = GameObject.Find("Camera");
instantiatedobjectsname.parent = camera.transform;
This is the main construct if I got you right, put your variables so the rest is yours.
You can use Camera.main to get the camera without Find. Avoid Find if you can, or use it in Start, but never Update.
Oh yes, definitely a better way to use Camera.main, thanks DaveA
Answer by DVFrance · Mar 07, 2015 at 07:36 PM
If I can just add a precision on byerdelen post. I'm using unity 4.6 (soon 5 :) ) and I need to wrote things like that :
GameObject myObjectToClone;
GameObject clone = Instantiate(myObjectToClone) as GameObject;
camera = GameObject.Find("Camera");
clone .transform.parent = camera.transform;
Answer by SchwertAs · Apr 08, 2017 at 11:04 PM
If you are using the editor extension feature when the game is not in run mode it is possible to insert an new object in the hierarchy permanently.
The code must be run by e. g. a button initiated procedure in a extension window. With the following steps it will do:
//search Father Obj
GameObject MyFatherObj = GameObjekt.Find("MyObjFatherName");
// create Obj in Top hierarchy with name New Game Object
GameObjekt myObj = new GameObject;
// push down in hierarchy
myObj.transform.parent = MyFatherObj.transform;
// rename
myObj.name = "MyObjName";