- Home /
how to instantiate an object that is a child of another object
I am trying to do a instantiate a game object to the child of another. It works, but every single gameobject I instantiate is in the same spot, when I want them to be in relation to their parent gameobject. The parent in my code would be "prefab" and the child that I am trying to make is "EmptyRayGameObject"
drones = new List<GameObject>();
for (int i = 0; i < droneCount; i++)
{
droneTemp = (GameObject) GameObject.Instantiate(prefab);
EmptyRayGameObject = (GameObject) GameObject.Instantiate (ePrefab);
I have tried this, and it kind of works, but still all the gameobjects are in the same spot, as opposed to being like 10 units in front of their parent gameobject.
EmptyRayGameObject.transform.parent = droneTemp.transform;
Answers I've tried (not succeeded)
drones = new List<GameObject>();
for (int i = 0; i < droneCount; i++)
{
droneTemp = (GameObject) GameObject.Instantiate(prefab);
EmptyRayGameObject = (GameObject) GameObject.Instantiate(ePrefab);
EmptyRayGameObject.transform.parent = droneTemp.transform;
EmptyRayGameObject.transform.localPosition = new Vector3(0.5f,0.5f,0.5f);
Answer by robertbu · Mar 14, 2014 at 06:20 PM
A solution is to use Transform.localPosition. For example:
drones = new List<GameObject>();
for (int i = 0; i < droneCount; i++)
{
droneTemp = (GameObject) GameObject.Instantiate(prefab);
EmptyRayGameObject = GameObject.Instantiate (ePrefab) as GameObject;
EmptyRayGameObject.transform.parent = someOtherTransform;
EmptyRayGameObject.transform.localPosition = new Vector3(0.5f,0.5f,0.5f);
The assigning of (0.5,0.5,0.5) to localPosition will make EmptyRayGameObject have that offset relative to the parent object.
I tried this and I got an error for the localPosition line, so I added a "new" before Vector3 to get rid of it. However, the position of the gameobject is still always in the same spot as the others.
Yea, you need to add 'new'. It is not necessary in Javascript, and as I switch back and forth answering questions I sometimes forget.
As for your problem. Are you sure you parented the object before you assigned the local position? Are you sure that the transform variable you are using for the parenting is not null? Is there any other code that might be positioning the object after its creation? 'localPosition' doesn't fail, so something else is going on here?
The is an alternate. Again say you wanted an offset from some other object. You can do your Instantiate like this:
Instantiate(eprefab, someOtehrTransform.position + offset, Quaternion.identity);
This form of Instantiate() takes the position and rotation, so you are setting position as you create the object.