Menu
CoddyTech

Destroy

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

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

The Chute drops a coin every second; that part is written. Change it so that:

  • each coin vanishes 3 seconds after it appears, so there are never more than 3 coins at once;
  • Space destroys the chute itself, so no more coins come. The coins already out still vanish on time.

Press Play, watch for a few seconds, press Space, 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
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics