Unity Collisions

DevGame DevUnity

OnTrigger collision callback demo in Unity

The aim of this post is to summarize:

  • What’s required for collisions in Unity
  • How to set up some basic collision detection
  • When OnTrigger and OnCollision are called, and when they aren’t

What’s required for a collision to occur?

For collisions to be detected by Unity, there are 2 components of particular importance:

1. Rigidbody

  • Allows an object to react to physics
  • A key property to note is isKinematic
  • If you do not require the object to have physics-based interactions with other objects (i.e. isKinematic is true), a Rigidbody is still required (on at least 1 object) for any collision to occur

2. Collider

  • Used to define the shape of the object (or rather an approximation of it) which will be used for collisions
  • There are various types of colliders, namely Box, Sphere, Capsule, Mesh, etc.
  • A key property to note is isTrigger

How do you set up basic collision detection?

1. When you need two solid objects to interact with each other

Object 1:

Sphere 1 Rigidbody and Collider setup

Object 2:

Sphere 2 Rigidbody and Collider setup

Notes:

  • At least one Rigidbody needs to be non-kinematic (i.e. isKinematic = false)

Callbacks that will be called:

  • OnCollisionEnter
  • OnCollisionExit

OnCollision callback demo

2. When you want to do something when a collision occurs (i.e. a trigger) on a non-physical object

Object 1:

Sphere 1 trigger setup

Object 2:

Sphere 2 trigger setup

Notes:

  • At least one object requires a RigidbodyisKinematic can be either true or false
  • At least 1 Collider needs to have isTrigger = true — both cannot be set to isTrigger = true

Callbacks that will be called:

  • OnTriggerEnter
  • OnTriggerExit

OnTrigger callback demo