Performance: OnCollisionEnter2D and OnTriggerEnter2D
This affects the physics simulation and event handling performance during gameplay, impacting frame rate and input responsiveness.
Jump into concepts and practice - no test required
void OnTriggerEnter2D(Collider2D other) {
// Simple trigger used for overlap detection
Debug.Log("Trigger entered by " + other.gameObject.name);
}void OnCollisionEnter2D(Collision2D collision) {
// Heavy physics collision used just to detect overlap
Debug.Log("Collision detected with " + collision.gameObject.name);
}| Pattern | Physics Cost | CPU Usage | Frame Impact | Verdict |
|---|---|---|---|---|
| OnCollisionEnter2D for overlap detection | High (full collision resolution) | High | Can cause frame drops | [X] Bad |
| OnTriggerEnter2D for overlap detection | Low (simple overlap check) | Low | Smooth frame rate | [OK] Good |
OnCollisionEnter2D is called when two solid objects collide physically, both having Rigidbody2D and Collider2D components without trigger enabled.OnTriggerEnter2D is called when an object enters a trigger collider, which is a collider set as a trigger, not a solid collision.OnTriggerEnter2D and it takes a Collider2D parameter.void OnTriggerEnter2D(Collider2D other). Other options have wrong parameter types or method names.void OnTriggerEnter2D(Collider2D other) {
Debug.Log("Trigger entered by " + other.name);
}
void OnCollisionEnter2D(Collision2D collision) {
Debug.Log("Collision with " + collision.gameObject.name);
}OnTriggerEnter2D method is called when an object enters a trigger collider. Since the collider is set as a trigger, this method will run.OnCollisionEnter2D only runs on solid collisions, not triggers. So it will not be called here.OnTriggerEnter2D method never runs when expected. What is the likely problem?
void OnTriggerEnter(Collider2D other) {
Debug.Log("Entered trigger");
}OnTriggerEnter2D. The code uses OnTriggerEnter, which is for 3D physics.Collider2D is correct for 2D triggers, but the method name mismatch prevents Unity from calling it.OnTriggerEnter2D in the player's script to detect when the player enters the collectible's trigger collider.