I have a GameObject that has a Rigidbody2D and a Collider2D. I have made a script that displays a slider in the Inspector to alter the Mass of the Rigidbody2D. That works.
I also want to alter the friction and bounciness of the Collider2D (without affecting the physicsMaterial2D in my assets whence they come). Is that possible? This code doesn’t do it:
private Collider2D col2D;
col2D = this.gameObject.GetComponent<Collider2D>();
col2D.sharedMaterial.bounciness = Bounciness; //Doesn't copy
Is there a way to do this?
Yes, you can alter the friction and bounciness of a Collider component attached to a game object from a script in Unity.
To do this, you can use the Collider.material property to get a reference to the PhysicMaterial associated with the Collider, and then use the PhysicMaterial.dynamicFriction and PhysicMaterial.staticFriction properties to set the dynamic and static friction, respectively. You can also use the PhysicMaterial.bounciness property to set the bounciness of the Collider.
public class MyScript : MonoBehaviour
// The amount of dynamic friction to set
public float dynamicFriction = 0.5f;
// The amount of static friction to set
public float staticFriction = 0.5f;
// The amount of bounciness to set
public float bounciness = 0.5f;
// Start is called when the script is first enabled
private void Start()
// Get the Collider component attached to the game object
Collider collider = GetComponent<Collider>();
// Check if the Collider component was found
if (collider != null)
// Get the PhysicMaterial associated with the Collider
PhysicMaterial material = collider.material;
// Set the dynamic and static friction of the PhysicMaterial
material.dynamicFriction = dynamicFriction;
material.staticFriction = staticFriction;
// Set the bounciness of the PhysicMaterial
material.bounciness = bounciness;