Set A Physics 2D material's values through script


I’m very new to unity programming and I’ve run into a problem recently with my movement system. Basically, the way I move characters is using Velocity (it’s what I decided to use because it’s the simplest for me) but it came with a problem: People can constantly press ‘A’ or ‘D’ against a surface and it will cause them to stick to the surface with no Y axis velocity. I’ve tried many different ways to fix this and all of them are very sloppy and don’t work seamlessly with my other mechanics. So I’m currently trying a new method; my idea is to set a Physics 2d Material friction to 0 while the player is in the air and set it back to normal (0.4) when the player is grounded. I already know how to detect if a player is in the air or not, the only problem I’m having is that I can’t figure out how to set a Physics 2D friction value through script.

Any help would be much appreciated.

Edit: “I guess to better explain it: I made a Physics 2D material that I want to be able to edit the friction values of using scripts (c#)”

Edit 2: “So I think I’ve figured out why that wasn’t working for me. If I understand this correctly I don’t believe I can constantly be changing the value of the friction, so, alternatively I need to figure out how to change a material applied to a collider/rigidbody through c# script…”

Ok, starting off by what you already know.
You want to change the PhysicsMaterial2D you either attached to the Rigidbody2D or any Collider2D. Accessing these would be either of the following:


According to the documentation (e.g. Unity - Scripting API: Collider2D), both have a property called sharedMaterial. And according to this (Unity - Scripting API: PhysicsMaterial2D), bounciness and friction are both public.
Putting everything together, that would make:

GetComponent<Rigidbody2D>().sharedMaterial.friction = x;
GetComponent<Collider2D>().sharedMaterial.friction = x;