Change a Collider 2D physics material at runtime?

If I change the physics material of a BoxCollider2D or EdgeCollider2D at runtime, it seems that the previous material is still used. I haven’t tested other colliders yet. The Inspector shows the correct material assigned (new one).

Test script:

public class AssignPhysicsMaterial : MonoBehaviour {
    public PhysicsMaterial2D mat;

    void Start() {
        collider2D.sharedMaterial = mat;
    }
}

For example, I created a PhysicsMaterial2D with Bounciness “1”. If I assign this material in the inspector before playing, the ball bounces continuously as expected. If I assign it at runtime through code, the ball doesn’t bounce, as if the default physics material is still being used (although inspector shows otherwise).

Is this a bug or have I missed something?

I emailed Unity support who agreed that this looks like a bug. I submitted a bug report and it’s been accepted.

The example project I submitted can be downloaded here.

This was fixed in 5.1.1p2 on the 26th June 2015.

Just tried this in Unity 5.6.2 and can confirm the bug still exists, @MelvMay using the following type of code, the material in the inspector changes but the previous material’s bouncy / friction are left in use.

void ChangeMat()
{
	if (useMat2)
	{ 
		rb.sharedMaterial = Resources.Load("Materials/Physics/mat2") as PhysicsMaterial2D;
	}
	else
	{
		rb.sharedMaterial = Resources.Load("Materials/Physics/mat1") as PhysicsMaterial2D;
	}
}

adding this code at the end works (warning, this crashes Unity like crazy):

rb.simulated = false;
rb.simulated = true;

I found that turning the collider on and off as suggested works well, using the following code:

cl.enabled = false;
cl.enabled = true;

The only problem with doing things like this is that if you happen to be in a 1 way collider and half or more of the collider you are enabling is in any of the 1way, your collider will jump to the top of the surface arc, something to bare in mind.