- Home /
Instantiate as a child at position
Alright so I'm trying to instantiate a gameobject as a child of another game object so that they will move together.
I also want it to be created in the center of the parent gameobject.
here is my code so far:
Instantiate(zap,Vector3(transform.position.x,transform.position.y,transform.position.z),transform.rotation);
zap.transform.parent = transform;
where zap is the game object I want to create. When I run this code it is run without an error, but I can't find the gameObject it has created and it doesn't seem to have become a child either. The gameObject instantiating zap is the object running the script. thank you
Answer by prof · Dec 24, 2013 at 08:22 AM
var newObj : Transform = Instantiate (zap, transform.position, transform.rotation) as Transform;
newObj.parent = transform;
When I run that code I get a
"Cannot convert 'UnityEngine.GameObject' to 'UnityEngine.Transform'."
error
var newObj : Transform = Instantiate (zap, transform.position, transform.rotation)as Transform;
then
Answer by johnCpr · Jun 14, 2018 at 05:31 PM
//for who checking this answer after couple of years
//Instantiate as a child at position
GameObject myPrf= Instantiate (myPrefab, transform.position - new Vector3(0,0,0), Quaternion.Euler(0, 0, 0));
myPrf.transform.parent = transform;
It's much better to use Transform.SetParent method because:
This method is the same as the parent property except that it is possible to make the Transform keep its local orientation rather than its global orientation.
Also I think you are missing 'as GameObject' in instantiation line. ;)
Your answer
Follow this Question
Related Questions
Position of a GameObject 2 Answers
Transform Checking on all Array Objects (JS) 3 Answers
Locating Position of Object not Working? 2 Answers