Change The Bounciness Of Physics Material 2d Randomly

Hey developers :slight_smile:
I am very new to unity so i appreciate every help I get from you.
Theres the problem:
The player is a ball and rolls into a direction. There shall be obstacles like incoming balls bouncing towards the player. Now i want that the obstacles have a different amount of bounciness between each one. I guess the best thing is to have a randomly generated number for the bounciness of the material.
I am pretty sure there’s a way to do it, but unfortunately I don’t know how it should work.
Can someone help me with that problem?
Greetings
BeatenByBacon

You can either create a bunch of physics materials beforehand in the editor, and then randomly select them from a list to apply to your rigidbody or collider…

Or you can change it in code when a ball is spawned:

public class BouncyBall : MonoBehaviour
{
    public float minBounciness = 0;
    public float maxBounciness = 10;

    private Rigidbody2D _rigidbody2D;

    private void Awake()
    {
        _rigidbody2D = GetComponent<Rigidbody2D>();
    }

    private void Start()
    {
        ApplyRandomlyBouncyMaterial();
    }

    private void ApplyRandomlyBouncyMaterial()
    {
        float randomBounciness = UnityEngine.Random.Range(minBounciness, maxBounciness);

        PhysicsMaterial2D newMaterial = new PhysicsMaterial2D("RandomlyBouncy");
        newMaterial.bounciness = randomBounciness;

        _rigidbody2D.sharedMaterial = newMaterial;
    }
}

You can also change an existing physics material at runtime, but i’d recommend using code to make a copy or constructing a new one as I’ve done here and altering that instead. PhysicsMaterials are assets in your project files so changes at runtime may persist after playmode in the editor. (haven’t confirmed that for phys materials specifically but thats generally what happens to assets edited during play mode such as materials and scriptable objects)

1 Like

Great! It just works amazing! Thank you so much!

1 Like