How to destroy a Gameobject in Unity.

Destroying gameobjects comes in handy in lot of game scenarios. Be it ammo collection or killing an enemy, destroying the object from the scene is a must learn skill. In this tutorial, we will see how to destroy a gameobject in your scene and other efficient ways to avoid garbage built-up.

Destroying a gameobject in Unity

You can destroy any object or component using the Destroy function in Unity. Destroy function takes two inputs. One is the gameobject to be destroyed and the other is the time delay in float.

Default syntax

Destroy(gameObject,timedelay);

Destroy any gameobject

Destroy(myobj);
//Give the name of your gameobject that you want to destroy in place of myobj

Destroy the Gameobject to which the script is attached

Destroy(this.gameObject);

Destroy Gameobject with a tag

Destroy(GameObject.FindWithTag("tag"));

Destroy the Script in which the code is present

Destroy(this);

Destroy any component attached to the gameobject

Destroy(GetComponent<Animator>());
//removes the animator component from the gameobject

Delay destruction of an object

Destroy(this.gameObject,10)
//destroys the gameobject after 10 seconds

Destroy Objects Immediately

The Destroy functions in Unity has a small delay but are generally executed within the same frame. Unity strongly recommends not to use Destroy immediate in games. You can destroy assets using Destroy immediate

DestroyImmediate(this.gameObject);

Things to know about destroying gameobjects in Unity

  1. Do not execute code in the same script after destroying the gameobject. This is a common mistake done by beginners. Once the script or game object is destroyed, none of the code inside the script will be executed.
  2. Destroy(this), destroys only the script not the gameobject.
  3. Destroying objects create a lot of garbage that effects performance.

Efficient way to remove object from scene

To reduce the dump created by destroying objects you can simply set the object as inactive. This way you need not instantiate a prefab when needed, you can just set the gameobject to active. You need not worry if you are destroying one or two gameobjects in a scene. The problem comes when you need to instantiate and destroy large number of objects like bullets in an FPS game.

Free Unity asset banner

Video Tutorial

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.