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. There are many resource guide on how to destroy the gameobject efficiently in Unity. In this tutorial, we will see how to destroy a gameobject in your scene and other efficient ways to avoid garbage builtup

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

Things to know about destroying gameobjects in Unity

  1. Do not execute code in the same script after destroying the gameobject.
  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 the gameobject when needed, you can just set it 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.

Leave a Reply

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