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\$
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
\$\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\$
  • \$\begingroup\$ And Do I need to attach the C# script to any Game Object ? \$\endgroup\$ – Gissipi_453 Mar 27 '15 at 5:50
  • \$\begingroup\$ Im getting this error - 'unity the thing you want to instantiate is null.' What does it mean ? \$\endgroup\$ – Gissipi_453 Mar 27 '15 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 Mar 27 '15 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 Mar 27 '15 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.