Unity – Destroy Components

Removes a gameobject, component or asset.

DESTROY OBJECT

DRAG AND DROP to an object in the Hierarchy

#pragma strict

function Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        Destroy(gameObject);
    }
}

Run and press Key to destroy object

DELAY DESTRUCTION

DRAG AND DROP to an object in the Hierarchy

#pragma strict

function Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        Destroy(gameObject,3f);
    }
}

Run and press Key to destroy object after 3 seconds ‘3f’

DESTROY OTHER OBJECTS

1. DRAG AND DROP to an object in the Hierarchy

#pragma strict

public var other : GameObject;


function Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        Destroy(other);
    }
}

2. Inspector> variable ‘Other’> small icon to select an object to destroy (onother object)

DESTROY COMPONENTS WITHOUT REMOVE OBJECT

1.DRAG AND DROP to an object in the Hierarchy

#pragma strict

function Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        Destroy(GetComponent(SpriteRenderer));
    }
}

2. Play, look at ‘Inspector’, and press ‘Space Bar’, the component ‘Sprite Renderer’ will disappear.

DESTROY EVERYTHING AHHH!!!! – EXAMPLES LIST

        // Kills the game object
	Destroy (gameObject);

	// Removes this script instance from the game object
	Destroy (this);

	// Removes the rigidbody from the game object
	Destroy (rigidbody);
	
	// Kills the game object in 5 seconds after loading the object
	Destroy (gameObject, 5);

	// When the user presses Ctrl, it will remove the script 
	// named FooScript from the game object
	function Update () {
		if (Input.GetButton ("Fire1") && GetComponent (FooScript))
			Destroy (GetComponent (FooScript));
	}