Instantiating a Prefab at Local position

Before anyone tells me to use the search bar, know that I have. Nothing I’ve found has helped. I’m just about ready to tear out my hair over this one…

Here is my code:

using UnityEngine;

using System.Collections;

public class InstantiatePrefab : MonoBehaviour {

public Transform thePrefab;
GameObject theObject;
// Use this for initialization
void Start () {
	theObject = (GameObject)Instantiate(thePrefab, transform.position,transform.rotation);
	theObject.transform.parent = transform;
	theObject.transform.localPosition = transform.localPosition;
	//Destroy (gameObject);


From what I’ve read, this SHOULD instantiate the object and ensure that it goes to the proper position. Indeed, it does go to my the instantiating object’s coordinates, but in WORLD space. I should mention that the object calling this script is a child of a Prefab. Any help would be greatly appreciated!

A bit old, but :

GameObject obstacle = Instantiate(prefabList[1], this.transform, false ) as GameObject;

the false for instantiateInWorldSpace avoids the prefabs position being concidered worldcoords.

Hey, it works for me. Script attached to object will be a parent.

var go = Instantiate (prefab, transform.position + new Vector3(x, y, z), Quaternion.identity);
go.transform.parent = transform;

The important part is: you have to add transform.position + before the new position so your code can actually use parent’s transform.position before placing new object. Notice, that the parent actually becomes the parent after instantiating so that’s why it uses world position to instantiate the object.

May be you can do like this…

theObject = Instantiate (currentPillar) as GameObject; 
theObject .transform.parent = parentObject.transform;
theObject.transform.localPosition = yourPosition;

Maybe I am not understanding you right. :slight_smile:

But the child’s local position is relative to the parent’s world position. So if you want the child to be at the same spot as the parent, you just have to set its local position to the zero vector.

If you change that vector, the child will move, but relative to the parent. You can just experiment with the values in the editor to understand what they mean. :slight_smile: