UNITY – JS Script – OnCollision – Destroy

1. Create a Sphere that falls and bource over a Cube (You have to use Physics 3D engine)

CASE 1: OnCollision -> Sphere will be destroyed

Attach to the Cube the script:

NOTICE: if you attach the script to the Sphere, it will not work! Because Sphere can not self collide!

#pragma strict

function OnCollisionEnter (col : Collision)
{
    if(col.gameObject.name == "Sphere")
    {
        Destroy(col.gameObject);
    }
}

Statement: gameObject.name == “Sphere” -> Use the ‘Hierarchy’ Name

CASE 2: OnCollision -> Cube will be destroyed

Attach to the Sphere the script:

NOTICE: if you attach the script to the Cube, it will not work!

#pragma strict

function OnCollisionEnter (col : Collision)
{
    if(col.gameObject.name == "Cube")
    {
        Destroy(col.gameObject);
    }
}

Statement: gameObject.name == “Cube” -> Use the ‘Hierarchy’ Name

CASE 3A: OnCollision -> Multiple Cube will be destroyed

1. Create a Sphere that falls and bource over Multiple Cubes (You have to use Physics 3D engine)
NOTICE: Every Cube can have different names

Attach to every Cubes the script:

#pragma strict

function OnCollisionEnter (col : Collision)
{
    if(col.gameObject.name == "Sphere")
    {
        // Destroy himself
        Destroy(gameObject);
    }
}

CASE 3B: OnCollision -> Multiple Cube will be destroyed

1. Create a Sphere that falls and bource over Multiple Cubes (You have to use Physics 3D engine)
NOTICE: Every Cube MUST have the same name (Cube)

Attach to the Sphere the script:

#pragma strict

function OnCollisionEnter (col : Collision)
{
    if(col.gameObject.name == "Cube")
    {
        // Destroy Cube
        Destroy(col.gameObject);
    }
}