Legacy Documentation: Version 2018.2 (Go to current version)
Time and Framerate Management
Coroutines
Other Versions

Creating and Destroying GameObjects

Some games keep a constant number of objects in the sceneA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary
, but it is very common for characters, treasures and other object to be created and removed during gameplay. In Unity, a GameObjectThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary
can be created using the Instantiate function which makes a new copy of an existing object:

public GameObject enemy;

void Start() {
    for (int i = 0; i < 5; i++) {
        Instantiate(enemy);
    }
}

Note that the object from which the copy is made doesn’t have to be present in the scene. It is more common to use a prefabAn asset type that allows you to store a GameObject complete with components and properties. The prefab acts as a template from which you can create new object instances in the scene. More info
See in Glossary
dragged to a public variable from the Project panel in the editor. Also, instantiating a GameObject will copy all the Components present on the original.

There is also a Destroy function that will destroy an object after the frame update has finished or optionally after a short time delay:

void OnCollisionEnter(Collision otherObj) {
    if (otherObj.gameObject.tag == "Missile") {
        Destroy(gameObject,.5f);
    }
}

Note that the Destroy function can destroy individual components without affecting the GameObject itself. A common mistake is to write something like:

 Destroy(this);

…which will actually just destroy the script component that calls it rather than destroying the GameObject the script is attached to.

Did you find this page useful? Please give it a rating:

Time and Framerate Management
Coroutines