< Return to Video

Detecting Collisions (OnCollisionEnter) - Unity Official Tutorials

  • 0:00 - 0:02
    Detecting a collision in Unity requires
  • 0:02 - 0:04
    one of the two colliding objects
  • 0:04 - 0:06
    to contain a script with an
  • 0:06 - 0:08
    OnCollisionEnter function in.
  • 0:08 - 0:10
    The basic syntax takes a single argument
  • 0:10 - 0:12
    of type Collision.
  • 0:13 - 0:15
    From this you can query the collision
  • 0:15 - 0:17
    to find out information about the object
  • 0:17 - 0:18
    that has been collided with.
  • 0:19 - 0:21
    In this example our samoflange ball is
  • 0:21 - 0:24
    bouncing around with a bouncy physic material
  • 0:24 - 0:26
    and hitting power cubes.
  • 0:27 - 0:30
    The script attached to the ball looks like this.
  • 0:31 - 0:33
    Currently we have nothing inside the function.
  • 0:33 - 0:35
    We can make use of the collision argument to
  • 0:35 - 0:37
    check for when it has hit a power cube.
  • 0:38 - 0:40
    We simply use an IF statement and check
  • 0:40 - 0:42
    'col', our variable, for the data
  • 0:42 - 0:45
    it contains. One example of which
  • 0:45 - 0:47
    is the game object that it's collided with
  • 0:47 - 0:50
    and as a result, the name. We would say
  • 0:50 - 0:54
    if(col.gameobject.name) is equal to
  • 0:54 - 0:56
    the hierarchical name of the power cube
  • 0:56 - 0:59
    which is 'prop_powercube'
  • 0:59 - 1:01
    and now this IF statement will only activate
  • 1:01 - 1:03
    when our ball collides with our power cube.
  • 1:03 - 1:05
    If it does collide, we'll make use of the
  • 1:05 - 1:07
    Destroy command. You can check what
  • 1:07 - 1:08
    types of data you can retrieve
  • 1:08 - 1:11
    from the collision by typing the name of the
  • 1:11 - 1:13
    variable and then typing a dot (period) in the script editor.
  • 1:14 - 1:15
    You'll then see a list of the various
  • 1:15 - 1:17
    different data you can retrieve from the collision.
  • 1:17 - 1:19
    Also remember to check the script reference
  • 1:19 - 1:21
    page linked below on the collision
  • 1:21 - 1:23
    class to see other data that you can retrieve.
  • 1:24 - 1:26
    For now we'll simply destroy the game object.
  • 1:27 - 1:29
    And when we save our script
  • 1:30 - 1:32
    you'll see that whenever a collision occurs
  • 1:32 - 1:35
    our ball destroys a power cube.
Title:
Detecting Collisions (OnCollisionEnter) - Unity Official Tutorials
Description:

more » « less
Video Language:
English
Duration:
01:43

English subtitles

Revisions