When changing a gameobjects layer, the physics collision matrix is not being respected immediately...

I’m working in 2D, so everything has 2D colliders.

I have a main character on the default layer. Then I have 3 additional layers, layerA, layerB and layerC. I have the collision matrix set so that layerA will collide with the default layer but the other two will not. I have a gameobject in each of the 3 layers.

I have it setup in code so that on a keypress that all 3 objects will shift their layers.

Character

Object1->LayerA

Object2->LayerB

Object3->LayerC

Then I press a key, it becomes this:

Character

Object1->LayerB

Object2->LayerC

Object3->LayerA

The character does not fall through Object1 once this happens though. Once I have my character jump off of Object1, he will then fall through until he hits Object2. If I have him simply move left and right along Object1 he will not fall. Only when he leaves the object for a second. Why is this? Is there a workaround?

I ran into this bug just now and found a good workaround for it. Try disabling then re-enabling the collider after setting the new layer.

this.gameObject.layer = LayerMask.NameToLayer("IgnoreAll");
this.collider2D.enabled = false;
this.collider2D.enabled = true;

Okay I found a workaround. Put transform.Translate(0,0,0) in the update() function of whatever object you’re trying to pass through. I’m not sure why this works, and it’s probably wasteful calling transform.Translate 60 times on every object, but for now it’ll do.Here’s the question/answer that I found the solution from.