instantiate object inside of another gameObject?

How is everyone this fine morning?

Is it possible to Instantiate a gameObject inside of another gameObject in the hierarchy?

if so how would I attempt it?

from the attached image I need to instantiate a gameObject inside of the EmptyGameObject where the other cubes are.
I know how to instantiate a gameObject in the scene but never had to do it inside of another gameObject before.

Thanks a million for any thoughts on how to do this.

771535--28236--$instantiate.png

3 Likes

var newObj = GameObject.Instantiate(somePrefabReference);
newObj.transform.parent = GameObject.Find(“EmptyGameObject”).transform;

8 Likes

Just set your newly instantiated object’s transform.parent field to the transform of the object want to, well, parent it to.

Example code from the manual:

// Makes the camera follow this object by
// making it a child of this transform.

// Get the transform of the camera
var cameraTransform = Camera.main.transform;     

// make it a child of the current object
cameraTransform.parent = transform; 

// place it behind the current object
cameraTransform.localPosition = -Vector3.forward * 5;

// make it point towards the object
cameraTransform.LookAt(transform);

If you want to move an object back to the root of the scene hierarchy, set it’s parent to null.

Unity Manual (Transform.parent): Unity - Scripting API: Transform.parent

1 Like

Ahhh Sweeet!

Thank you andorov greatly appreciated!!!

I know that it’s old question but for people which will look for this in the future.
Now You should do it like that:

Transform Parent;
GameObject PrefabGameObject;

GameObject InstantiatedGameObject= Instantiate(PrefabGameObject);
InstantiatedGameObject.transform.SetParent(Parent);

More about it here Unity - Scripting API: Transform.SetParent

Or just use second parameter in Instantiate function like this

Transform Parent;
GameObject PrefabGameObject;

Instantiate(PrefabGameObject,Parent);

More here Unity - Scripting API: Object.Instantiate

9 Likes

I know this is an ancient thread, but in case anyone runs into this issue and none of the suggestions on various forums work, the following worked for me:

Instantiate(instantiatedObject, Vector3 position, Quaternion rotation, parentGameObject);

And I just made the parent game object a public variable. Don’t know if it’s a version mismatch or what, but the Unity documentation on the overloads for this function were incorrect for me, stating that the parent needs to be set BEFORE position and after the instantiated object, whereas it actually needed to be set after rotation.

4 Likes

thanks mate!, 8 years later

2 Likes

Thanks guys! 12 years later. BTW I’m in the time where Unity put the fee installation.

That’s enough pointless necroing. Closing the thread.

1 Like