[Unity 3D] Dynamically modify collider 2D

Problem

You would like to modify/update game object’s collider (EdgeCollider2D) from the code behind. Collider is marked as “Is Trigger” but you are not getting any events (like OnTriggerEnter2D, OnTriggerStay2D or OnTriggerExit2D).

Why

Took me at least few hours to find out that collider cannot be inside other collider, otherwise (apparently) Unity will optimize it and remove it.

Solution

When you add collider that you want to modify in runtime, make sure it’s outside of another one. On the picture below you will see I am using BoxCollider around player. Inside it I added EdgeCollider 2D that I wanted to update when user is moving. When EdgeCollider was inside BoxCollider, it didn’t trigger any events. If you move it outside of it, everything will start working.

 

Notes

EdgeCollider 2D will “collide” however when “Is Trigger” is not marked. Then his initial position can be inside of the other collider.

Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>