-
Detecting a collision in Unity requires
-
one of the two colliding objects
-
to contain a script with an
-
OnCollisionEnter function in.
-
The basic syntax takes a single argument
-
of type Collision.
-
From this you can query the collision
-
to find out information about the object
-
that has been collided with.
-
In this example our samoflange ball is
-
bouncing around with a bouncy physic material
-
and hitting power cubes.
-
The script attached to the ball looks like this.
-
Currently we have nothing inside the function.
-
We can make use of the collision argument to
-
check for when it has hit a power cube.
-
We simply use an IF statement and check
-
'col', our variable, for the data
-
it contains. One example of which
-
is the game object that it's collided with
-
and as a result, the name. We would say
-
if(col.gameobject.name) is equal to
-
the hierarchical name of the power cube
-
which is 'prop_powercube'
-
and now this IF statement will only activate
-
when our ball collides with our power cube.
-
If it does collide, we'll make use of the
-
Destroy command. You can check what
-
types of data you can retrieve
-
from the collision by typing the name of the
-
variable and then typing a dot (period) in the script editor.
-
You'll then see a list of the various
-
different data you can retrieve from the collision.
-
Also remember to check the script reference
-
page linked below on the collision
-
class to see other data that you can retrieve.
-
For now we'll simply destroy the game object.
-
And when we save our script
-
you'll see that whenever a collision occurs
-
our ball destroys a power cube.