Create and destroy GameObjects runtime in Unity C#

By Faruque Ahamed Mollick

In game development, there are often need to create and destroy GameObjects in runtime. For example, in car racing game, all the object are not already built in the scene. Those objects will not be available when we start the game. It created when we need it during the gameplay.

Similarly, in a game, it often needed to destroy some object during gameplay. For example, killing enemies when bullet attacks them will destroy them.

So there are often some GameObjects available in a game which to be created and removed during playing the game.

So in this tutorial, I am going to show you how to create and destroy GameObjects runtime in Unity C#.

C# code to create and destroy GameObjects during gameplay

First let’s see, how we can create our GameObjects in unity using C#. Here I am going to show you two different way of creating GameObject with coding.

Example 1: Creating by declaring the primitive type variable

public GameObject capsule;
void Start() {

    for (int i = 0; i < 10; i++) {
      GameObject.CreatePrimitive(PrimitiveType.Capsule);
    }

}

In this example, we have created the gameObject completely with C# coding. GameObjects are primitive type data.

 

Example 2: Creating GameObject with prefab (Alternative method)

Prefab is one of my favorite feature that is available in Unity. You can create the prefab of your GameObject. Prefab stores the object with its style, size, and components etc All you need just drag and drop it to the script and use it inside the script. Below is the code snippet:



public GameObject enemy;

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

The “enemy” here is the Prefab that we have previously created and drag it to the script.

 

Destroying GameObject in Unity using C#

Destroying a game object in unity is quite easy. Suppose, you want to destroy an object when it collides with another object having tag name “Enemy” and you want to destroy it. So below is the C# code snippet that will destroy the object:

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

In the above code, we have used the OnCollisionEnter function that is built in part of Unity. To know more about this function and its usage I recommend you read this post – Detect collision with a specific object in Unity 3D C#.

So in this post, we have learned how to create and destroy GameObjects runtime in Unity. Try it yourself and let me know if you face any problem.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *