Menu
CoddyTech

Destroy

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 67 of 85.

Destroy(obj) removes a GameObject from the scene, children included. A second argument delays it: Destroy(obj, 2f) removes it 2 seconds from now, and the script that called it carries on at once. This cannon fires on Space, and each bullet it makes is gone 2 seconds later:

public GameObject bulletPrefab;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
        Destroy(bullet, 2f);
    }
}

Pass the copy, not the prefab: Destroy(bulletPrefab) is refused with Destroying assets is not permitted to avoid data loss. And pass a GameObject when you mean the object. Inside a script, gameObject is the object the script is on, so Destroy(gameObject) removes that object, while Destroy(this) removes only the script and leaves the object standing.

Destroy never happens on the spot. Unity removes the object at the end of the current frame, after the frame's Update() and LateUpdate() calls, so the lines after Destroy still run and the object can still be found until the frame is over.

challenge icon

Challenge

Medium

Clear the old coins away, and let Space remove the chute.

  1. Keep the new coin, GameObject coin = Instantiate(...);, then call Destroy(coin, 3f);.
  2. On Input.GetKeyDown(KeyCode.Space), call Destroy(gameObject);. Destroy(this) would remove only the script.

Press Play: each coin vanishes after 3 seconds, and Space stops new ones. Then Check.

Try it yourself

using UnityEngine;

public class CoinChute : MonoBehaviour
{
    public GameObject coinPrefab;
    public float interval = 1f;
    float timer;

    void Update()
    {
        timer += Time.deltaTime;
        if (timer >= interval)
        {
            Instantiate(coinPrefab, transform.position, Quaternion.identity);
            timer -= interval;
        }

        // Space: destroy the chute
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground