Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to change physics material at runtime?

Discussion in 'Scripting' started by Derek_aka_Derek, Mar 11, 2021.

  1. Derek_aka_Derek

    Derek_aka_Derek

    Joined:
    Jun 15, 2018
    Posts:
    2
    please write example code that changes a capsule colliders physics material from "playerFriction" to "playerSlide". I'm seriously not getting this and all the other threads are from 2013 with all of the code being deprecated.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
  3. Derek_aka_Derek

    Derek_aka_Derek

    Joined:
    Jun 15, 2018
    Posts:
    2
    Nice, that's not what the old guides say. So I already have a physics material I want to apply, how would I "load" it in the script so I can apply it? Do I have to create the physics materials in the script? can it not pull the ones I created from my project file?
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    You can create a public/serialized PhysicMaterial field and reference it in your script like any other unity object such as Textures, Meshes, Components, etc...
     
  5. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    Code (CSharp):
    1.     public class Foo : MonoBehaviour
    2.     {
    3.         public PhysicMaterial someMaterial; //assigned in the editor
    4.  
    5.         public void ChangeMaterial()
    6.         {
    7.             var collider = GetComponent<Collider>();
    8.             collider.sharedMaterial = someMaterial;
    9.         }
    10.     }
    11.  
     
    zzourss and Mart0_M like this.