Search code examples
unity-game-engine

Set Collider2D friction at runtime without modifying Physics2D material


I have a set of objects that all share the same physics configurations and therefore a single Physics2D material. Multiple of these objects can be active on a scene at the same time.

I would like to change the friction of these objects at runtime in a way that's independent of each other. When I use Collider2D.sharedMaterial property this seems to change the material itself and that material as I mentioned is used in many other objects. Is there a way I can update the friction of the objects at runtime in a way that's independent of each other?

If this can be accomplished while still using a Physics2D material great. If not, I'm also OK on not using one, but in that case, I can't figure out how to set the friction of an object as the Collider2D.friction property seems to be read-only unlike the Collider2D.sharedMaterial.friction property.


Solution

  • Other than for Collider (3D) there unfortunately is no material property for Collider2D that automatically would instantiate a copy of the material like you expect.

    You could though do this "manually" using e.g.

    var material = someCollider2D.sharedMaterial;
    var copyMaterial = Instantiate(material);
    // Make some modifications 
    someCollider2D.sharedMaterial = copyMaterial;
    

    And/Or alternatively if you already know beforehand you will need a fixed set of different settings you could of course also already beforehand simply create all the required physics material assets and reference them all in fields via the Inspector

    [SerializeField] PhysicsMaterial2D defaultMaterial;
    [SerializeField] PhysicsMaterial2D slippyMaterial;
    

    and later assign them how and where required

    someCollider2D.sharedMaterial = slippyMaterial;