7

How do you do. I want to create a new gameobject and then add the gameobject in scene.

How do I do this?

My code is:

GameObject a = new GameObject();
GameObject aClone = Instantiate(a) as GameObject;

but doesn't work correctly.

0

2 Answers 2

16

The correct way:

GameObject obj = Instantiate(prefab) as GameObject;

You can specify the position and the rotation as well.

Vector3 position    = new Vector3(1, 1, 1);
Quaternion rotation = new Quaternion(1, 1, 1, 1);
GameObject obj      = Instantiate(prefab, position, rotation) as GameObject;

Obviously use the position and rotation that you like by changing the parameters.

A prefab is simply:

public GameObject prefab;

Drag a GameObject into the script via the Editor.

Sign up to request clarification or add additional context in comments.

1 Comment

Can I have a new GameObject without having a prefab?
0

Instantiate takes 3 arguments, the gameObject, the position and the rotation. This will put it in your scene depending on what you parse in as values.

Instantiate(a, Vector3 (x, y, z), Quaternion.identity);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.