0
0
UnityHow-ToBeginner ยท 3 min read

How to Use Destroy in Unity: Syntax, Examples, and Tips

In Unity, use Destroy(object) to remove a game object or component from the scene. You can optionally specify a delay with Destroy(object, delay) to destroy it after some seconds.
๐Ÿ“

Syntax

The Destroy function removes a game object or component from the scene. It has two common forms:

  • Destroy(object); - destroys at the end of the current frame.
  • Destroy(object, delay); - destroys after delay seconds.

object can be a GameObject or any Component like Transform or Collider.

delay is a float specifying seconds to wait before destruction.

csharp
Destroy(gameObject);
Destroy(gameObject, 2.0f);
๐Ÿ’ป

Example

This example shows how to destroy a game object 3 seconds after the game starts. It demonstrates delayed destruction using Destroy.

csharp
using UnityEngine;

public class DestroyExample : MonoBehaviour
{
    void Start()
    {
        // Destroy this game object after 3 seconds
        Destroy(gameObject, 3f);
    }
}
Output
The game object this script is attached to will be removed from the scene 3 seconds after the game starts.
โš ๏ธ

Common Pitfalls

  • Destroying null objects: Calling Destroy on a null reference does not cause errors but does nothing.
  • Destroying components vs game objects: Destroying a component removes only that component, not the whole object.
  • Immediate destruction misunderstanding: Destroy actually destroys the object at the end of the frame, not instantly.
  • Accessing destroyed objects: Avoid using objects after calling Destroy on them.
csharp
/* Destroying null object does nothing, no error */
GameObject obj = null;
Destroy(obj); // Safe, does nothing

/* Right: Check before destroying if you want to avoid unnecessary calls */
if(obj != null) {
    Destroy(obj);
}
๐Ÿ“Š

Quick Reference

Remember these tips when using Destroy:

  • Use Destroy(gameObject) to remove the whole object.
  • Use Destroy(component) to remove only that component.
  • Use the delay parameter to postpone destruction.
  • Checking for null before destroying is optional but can avoid unnecessary calls.
  • Objects are destroyed at the end of the frame, not immediately.
โœ…

Key Takeaways

Use Destroy(object) to remove game objects or components safely in Unity.
You can delay destruction by passing a second float parameter for seconds.
Destroy does not remove objects instantly but at the end of the current frame.
Destroying a null object does not cause errors but does nothing.
Destroying a component removes only that component, not the entire game object.