Detect contact between 2D Physics Core objects
Detect when 2D Physics Core objects make contact, and respond to collision events and trigger events.
Read time 1 minuteLast updated 15 days ago
To detect contact between 2D Physics Core objects, use either of the following approaches:
- Detect a contact event or trigger event.
- Check whether 2D physics objects overlap or will collide, also known as intersections. For more information, refer to .
PhysicsQuery
Detect contact
To detect when objects make contact, enable Unity reporting collision events or trigger events. Follow these steps:
-
Create a GameObject with a script that implements theor
PhysicsAreaCallbacks.IContactCallbackinterface, and a callback method. For example:PhysicsAreaCallbacks.ITriggerCallbackpublic class DetectCollisions : MonoBehaviour, PhysicsAreaCallbacks.IContactCallback{ public void OnContactBegin2D(PhysicsAreaCallbacks.ContactBeginEvent beginEvent) { Debug.Log("Contact started between areas: " + beginEvent.areaA + " and " + beginEvent.areaB); }}For more information, refer to.PhysicsAreaCallbacks.ContactBeginEvent -
Select the GameObject you want to detect contact for.
-
In thewindow, expand the Definition section of the Physics Area component.Inspector
?
-
Enable Contact Events or Trigger Events.
-
In the Callbacks section, set Callback Source to Area.
-
Set Callback Target to the GameObject with the script you created in step 1.
If two areas that have either property enabled make contact, they both report the event to Unity.
To run a method or set a parameter you select in the Inspector window instead, set Callback Source to Events and use the properties in the Event settings section.