Unity – Destroy Components

Removes a gameobject, component or asset.

DESTROY OBJECT

DRAG AND DROP to an object in the Hierarchy

1
2
3
4
5
6
7
8
9
#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

1
2
3
4
5
6
7
8
9
#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

1
2
3
4
5
6
7
8
9
10
11
12
#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

1
2
3
4
5
6
7
8
9
#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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    // 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));
}