- Home /
How to select a gameobject by script dynamically
I would like to select a gameobject and put it in scene (maybe multiple times)(dynamically).
In editor , i can drag it to the scene.
But i have no idea to do it by script(C#) dynamically.
Which function i should use ?
Can anyone solve this problem?
I have learnt Java for 2 yrs, in my understanding, I treat the teapot (in the picture) as a class, and i can create many objects of the teapot. Is this logic right?
You need to make it into a prefab then instantiate this prefab at runtime. Look up "Prefabs" and "Instantiate" in the Unity Docs for detailed information :)
@EdwardLee, please watch the Unity Learning videos, it will help so much, as for Prefabs as @$$anonymous$$rSoad mentioned, there's a video for that here.
Answer by dfsp_spirit · Sep 14, 2016 at 12:25 PM
1) Create a prefab
I would suggest to create an empty folder assets/prefabs/ first. Then add a game object to your scene manually in the editor and prepare it the way you want it (animations, maybe movement script, etc.) Then draw the finished template into the assets/prefabs/ folder.
You can now delete the original object from the scene.
2) Use a script to create instances of the prefab dynamically
Here is an example script, taken from the Unity Manual, Section Instantiating Prefabs:
// Instantiates a prefab in a grid
public GameObject prefab;
public float gridX = 5f;
public float gridY = 5f;
public float spacing = 2f;
void Start() {
for (int y = 0; y < gridY; y++) {
for (int x = 0; x < gridX; x++) {
Vector3 pos = new Vector3(x, 0, y) * spacing;
Instantiate(prefab, pos, Quaternion.identity);
}
}
}
You can drag & drop your prefab on the public prefab variable in the Unity editor.