7
\$\begingroup\$

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

\$\endgroup\$

3 Answers 3

7
\$\begingroup\$

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 =
            Instantiate(Resources.Load("road"),
            new Vector3(5, 5, 5),
            Quaternion.identity) as GameObject;
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Unity's best practices notes that Resources should be avoided: unity3d.com/learn/tutorials/topics/best-practices/…. I believe that in this case it would be preferable to have the road Prefab placed as a component parameter (if possible). \$\endgroup\$ Commented Oct 26, 2016 at 23:23
1
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$
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.

\$\endgroup\$
4
  • \$\begingroup\$ And Do I need to attach the C# script to any Game Object ? \$\endgroup\$ Commented Mar 27, 2015 at 5:50
  • \$\begingroup\$ Im getting this error - 'unity the thing you want to instantiate is null.' What does it mean ? \$\endgroup\$ Commented Mar 27, 2015 at 6:26
  • \$\begingroup\$ you should have a public var GameObject and drag your prefab there in the editor. Then Instantiate that var \$\endgroup\$
    – Leggy7
    Commented Mar 27, 2015 at 6:33
  • \$\begingroup\$ 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. \$\endgroup\$
    – Gnemlock
    Commented Mar 27, 2015 at 6:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .