How to destroy a Gameobject in Unity.

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

We will also go through the syntax for using the destroy method for different scenarios. To test the below code, create a new scene, add the default Unity cube or an empty game object and add a new script to it. 

Destroying a game object in Unity

You can destroy any object or component using the Destroy function in Unity. Destroy function takes two inputs. First input is the game object to be destroyed and the second is the time delay in float. The second argument is not mandatory for the actual object destruction.

Default syntax

Destroy(gameObject,timedelay);

Destroy any gameobject with all its components

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

Destroy the Game object to which the script is attached

Destroy(this.gameObject);

Destroy other objects with tag

GameObject.Find is very performance expensive. Avoid it inside the void Update function.

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

To Destroy an object with its name, use GameObject.Find in place of GameObject.FindWithTag.

Destroy the Script in which the code is present

The following code will only destroy the script and not the game object.

Destroy(this);

Destroy any component attached to the game object

Destroy(GetComponent<Animator>());
//removes the animator component from the game object
You can use this line of code to destroy any component in Unity like Collider components, rigid body 

Delay destruction of an object

Destroy(this.gameObject,10)
//destroys the game object 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);

Destroy Parent Objects

Destroy(transform.parent.gameObject);

The above code will destroy the parent game object. Use it with caution as this will also destroy the other children game object sharing the common parent.

Destroy Child of a Game object

To destroy a child game object in Unity, use the transform children property, you can iterate through the child objects and destroy them individually. This method removes all children objects one by one.

int childCount = transform.childCount;
        for (int i = childCount - 1; i >= 0; i--)
        {
            Transform child = transform.GetChild(i);
            Destroy(child.gameObject); // Destroy the child object
        }

Important things to know about destroying game objects in Unity

  1. Do not execute code in the same script after destroying the game object. 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 component and not the game object.
  3. Destroying game objects create a lot of garbage that effects performance.
  4. Using the destroy method in the void Start function will destroy the object immediately. But this can be used to destroy duplicate script instance when using DonDestroyOnLoad

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 game object to active. You need not worry if you are destroying one or two game objects in a scene. The problem comes when you need to instantiate and destroy large number of objects like bullets in an FPS game.

Disabling vs Destroying an Object

Disabling an object means that the object is still present in the scene but its components, scripts, and rendering are temporarily turned off. On the other hand, destroying an object completely removes it from the scene, freeing up memory and resources.

When it comes to performance, disabling an object can provide a significant improvement compared to destroying it. Here’s why:

  1. Memory Efficiency: Disabling an object keeps its data in memory, allowing you to easily re-enable it later without the need to recreate or reload its information. This can be beneficial if you frequently enable and disable objects during gameplay, as it avoids the overhead of constantly spawning and destroying them.
  2. CPU Efficiency: Disabling an object stops its associated scripts and components from running updates and calculations. This can reduce the workload on the CPU, especially for complex or resource-intensive scripts. By disabling objects that are not currently needed, you can optimize the performance of your game by reducing unnecessary computations.
  3. Smooth Transitions: Disabling an object instead of destroying it can be useful for achieving smooth transitions between different states or levels in your game. For example, if you have a character that moves between different scenes, disabling it when transitioning ensures that its state is preserved, and it can seamlessly continue from where it left off when re-enabled.
  4. Preservation of Relationships: Disabling an object maintains its relationships with other objects in the scene. If you have references to the disabled object from other scripts or components, those references will still be valid when you re-enable the object. This can be beneficial in scenarios where you need to preserve and restore specific object hierarchies or connections.

Disabling an object in Unity provides performance benefits by conserving memory, reducing CPU workload, enabling smooth transitions, and preserving object relationships. It allows for efficient management of game objects and can contribute to a smoother and more optimized gameplay experience.

Video Tutorial

For the next tutorial, we will learn about materials and textures in Unity.

Leave a Reply

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

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading