How can i change the bouncinnes on a PhysicMaterial2D in runtime?

Hi , I’m new in unity scripting and I’ve been trying to change the bounciness of a material with a script. I want to either change the bounciness or swap the material from one with 0 bounciness to another with bounciness 1. I’ve been looking in the unity documentation and trying but i cant get it to work. If someone could help me please , i appreciate it.

Hi dear,
To change the bounciness of a PhysicMaterial2D in Unity, you can use the bounciness property of the material. Here’s an example script that changes the bounciness of a material:

using UnityEngine;

public class ChangeBounciness : MonoBehaviour
{
    public PhysicMaterial2D materialWithBounciness1;
    public float newBounciness;

    void OnCollisionEnter2D(Collision2D collision)
    {
        // Check if the collision involves the object this script is attached to
        if (collision.gameObject == gameObject)
        {
            // Get the current material of the collider that was hit
            Collider2D collider = collision.collider;
            PhysicMaterial2D currentMaterial = collider.sharedMaterial as PhysicMaterial2D;

            // Check if the current material has a bounciness property
            if (currentMaterial != null && currentMaterial.bounciness != newBounciness)
            {
                // Change the bounciness of the material
                currentMaterial.bounciness = newBounciness;

                // Alternatively, you can swap the material to one with bounciness 1
                if (newBounciness == 1)
                {
                    collider.sharedMaterial = materialWithBounciness1;
                }
            }
        }
    }
}