Destroy

Tutorial

·

Beginner

·

+10XP

·

5 mins

·

(2242)

Unity Technologies

Destroy

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

This tutorial is included in the Beginner Scripting project.

Previous: Linear Interpolation

Next: GetButton and GetKey

Languages available:

1. Destroy

DestroyBasic

using UnityEngine;
using System.Collections;

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

DestroyOther

using UnityEngine;
using System.Collections;

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

DestroyComponent

using UnityEngine;
using System.Collections;

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

Complete this tutorial