Consider this Unity C# script attached to a GameObject with a Rigidbody2D and Collider2D (not set as trigger). What will be printed when this object collides with another object?
using UnityEngine; public class CollisionTest : MonoBehaviour { void OnCollisionEnter2D(Collision2D collision) { Debug.Log($"Collided with {collision.gameObject.name}"); } void OnTriggerEnter2D(Collider2D other) { Debug.Log($"Triggered by {other.gameObject.name}"); } }
Think about the difference between a collider set as trigger and a normal collider.
OnCollisionEnter2D is called when two colliders collide and at least one has a Rigidbody2D and neither collider is set as trigger. OnTriggerEnter2D is called only if one collider is set as trigger. Since the collider is not a trigger, only OnCollisionEnter2D runs.
Given this script on a GameObject with a Collider2D set as trigger and a Rigidbody2D, what will be printed when another GameObject enters its trigger area?
using UnityEngine; public class TriggerTest : MonoBehaviour { void OnCollisionEnter2D(Collision2D collision) { Debug.Log("Collision detected"); } void OnTriggerEnter2D(Collider2D other) { Debug.Log($"Entered trigger by {other.gameObject.name}"); } }
Remember which method is called for trigger colliders.
OnTriggerEnter2D is called when a collider marked as trigger is entered by another collider. OnCollisionEnter2D is not called for triggers.
A developer wrote this script but OnTriggerEnter2D never runs when expected. What is the most likely reason?
using UnityEngine; public class TriggerDebug : MonoBehaviour { void OnTriggerEnter2D(Collider2D other) { Debug.Log("Trigger entered"); } }
Check the collider settings on the GameObject.
OnTriggerEnter2D only runs if the collider is set as trigger. If the collider is not a trigger, this method won't be called.
Choose the correct statement about how Unity calls OnCollisionEnter2D and OnTriggerEnter2D methods.
Think about the role of triggers and Rigidbody2D in collision and trigger events.
OnTriggerEnter2D is called when a collider marked as trigger is entered by another collider that has a Rigidbody2D. OnCollisionEnter2D is called when two colliders collide and neither is a trigger.
Analyze the following script attached to a GameObject with a Rigidbody2D and a Collider2D set as trigger. Another GameObject with Rigidbody2D and a normal collider collides with it. What will be printed?
using UnityEngine; public class MixedCollision : MonoBehaviour { void OnCollisionEnter2D(Collision2D collision) { Debug.Log("Collision detected"); } void OnTriggerEnter2D(Collider2D other) { Debug.Log("Trigger detected"); } }
Remember how Unity treats collisions between trigger and non-trigger colliders.
When one collider is a trigger and the other is not, OnTriggerEnter2D is called on the trigger collider's script. OnCollisionEnter2D is not called.