# How do I instantiate a prefab to a specific coordinate?

I have a prefab called ‘road’. How can I instantiate it (using C#) such that it appears initially at coordinates (5, 5, 5)?

If you put the prefab into a directory called Resources inside your Assets directory, you'll be able to use the Resources class and its load functionality. This will load a prefab up as a GameObject, which can then be instantiated.

For example:

GameObject myRoadInstance = Instantiate(Resources.Load("road")) as GameObject;


Will create a instance of your "road" prefab in the game world.

You can either set its position by modifying its transform, or you can use the alternate version of Instantiate to specify a position.

GameObject myRoadInstance =
new Vector3(5, 5, 5),
Quaternion.identity) as GameObject;


The Unity Manual contains an example:

public class ExampleClass : MonoBehaviour {
public Transform prefab;
void Start() {
for (int i = 0; i < 10; i++) {
Instantiate(prefab, new Vector3(i * 2.0F, 0, 0), Quaternion.identity);
}
}
}


Note the vector3 passed as the second parameter and the quaternion as the third.

Vector3 position = new Vector3(5, 5, 5);

GameObject newGameObject = Instantiate(GameObjectToInstantiate);

newGameObject.transform.position = position;


You will always need to know what your going to instantiate, but from there you just call Instantiate as a function and load it into a new gameObject. You have to position it separately.

• And Do I need to attach the C# script to any Game Object ? – Gissipi_453 Mar 27 '15 at 5:50
• Im getting this error - 'unity the thing you want to instantiate is null.' What does it mean ? – Gissipi_453 Mar 27 '15 at 6:26
• you should have a public var GameObject and drag your prefab there in the editor. Then Instantiate that var – Leggy7 Mar 27 '15 at 6:33
• as Leggy said, making that initial placeholder a public and dragging in the reference in unity is the easiest way to get it going. Later on you can use programming to do this more securely, but any more work is probably counterproductive for the purpose of what your trying to do. – Gnemlock Mar 27 '15 at 6:47