Scripting
Beginner

Destroy

Checked with version: 4

-

Difficulty: Beginner

-

Date: 27 Apr 2015

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

Destroy

Beginner Scripting

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]())
Linear Interpolation
GetButton and GetKey

Related documentation

Got it

The Unity Software License Agreement and Privacy Policy have been updated.

We use cookies to ensure that we give you the best experience on our website. Click here for more information.