Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create a new gameobject and add the gameobject in scene Unity3d

Tags:

c#

unity3d

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.

like image 872
MGServices Avatar asked Nov 05 '14 03:11

MGServices


1 Answers

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.

like image 185
apxcode Avatar answered Sep 21 '22 16:09

apxcode