Destroy

Checked with version: 4.0

-

Difficulty: Beginner

-

Date: 13 Mar 2014

How to use the Destroy() function to remove GameObjects and Components at runtime.

DestroyBasic

Code snippet

using UnityEngine;
using System.Collections;

public class DestroyBasic : MonoBehaviour
{
    void Update ()
    {
        if(Input.GetKey(KeyCode.Space))
        {
            Destroy(gameObject);
        }
    }
}
#pragma strict

function Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        Destroy(gameObject);
    }
}
import UnityEngine
import System.Collections


public class DestroyBasic(MonoBehaviour):

    private def Update():
        if Input.GetKey(KeyCode.Space):
            Destroy(gameObject)

DestroyOther

Code snippet

using UnityEngine;
using System.Collections;

public class DestroyOther : MonoBehaviour
{
    public GameObject other;
    
    
    void Update ()
    {
        if(Input.GetKey(KeyCode.Space))
        {
            Destroy(other);
        }
    }
}
#pragma strict

public var other : GameObject;


function Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        Destroy(other);
    }
}
import UnityEngine
import System.Collections


public class DestroyOther(MonoBehaviour):

    public other as GameObject

    
    
    private def Update():
        if Input.GetKey(KeyCode.Space):
            Destroy(other)

DestroyComponent

Code snippet

using UnityEngine;
using System.Collections;

public class DestroyComponent : MonoBehaviour
{
    void Update ()
    {
        if(Input.GetKey(KeyCode.Space))
        {
            Destroy(GetComponent<MeshRenderer>());
        }
    }
}
#pragma strict

function Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        Destroy(GetComponent(MeshRenderer));
    }
}
import UnityEngine
import System.Collections


public class DestroyComponent(MonoBehaviour):

    private def Update():
        if Input.GetKey(KeyCode.Space):
            Destroy(GetComponent[of MeshRenderer]())
Lerp
GetButton and GetKey

Related documentation

Destroy (Script Reference)