- Home /
how to change physics material of a colider in runtime
hello I was wondering if I can change the physics material of an object's colider. for example, changing it from metal to bouncy. is it even possible?
Answer by Robotron18 · Nov 08, 2010 at 11:02 AM
You can pre-create the desired material in the editor Unity or use available in "Assets/Standard Assets/Physic Materials". Then place it into "Assets/Resources/PhysicMaterials". And for runtime change:
gameObject.collider.material = (PhysicMaterial)Resources.Load("PhysicMaterials/Wood");
Use the following code to assign when you import resources:
public void OnPostprocessModel(GameObject importedObject)
{
CapsuleCollider capColl = importedObject.AddComponent<CapsuleCollider>();
capColl.material = (PhysicMaterial)Resources.Load("PhysicMaterials/Wood");
}
This doesn't seem to work for me. I keep getting an error message saying the editor is expecting a semicolon on line 78, which ends up being in between the E and the S in the word Resources.
Anyone have any ideas?
Answer by Eric5h5 · Apr 01, 2010 at 05:44 PM
Yes, you can change collider.material
, by either assigning a PhysicMaterial:
var myMaterial : PhysicMaterial;
function Start () { collider.material = myMaterial; }
or changing individual properties (collider.material.bouncyness
, etc.).
Answer by sathya _m · Oct 31, 2013 at 12:46 PM
In c#
this.collider.material=new PhysicMaterial("Wood");
But don't forgot we need to refresh rigidbody for applying changes.
before change: rigidbody.isKinematic = true ; rigidbody.Sleep();
after change: rigidbody.isKinematic = false ; rigidbody.Wakeup();
Answer by KvanteTore · Apr 01, 2010 at 05:51 PM
Yes, that is possible. You can set the active PhysicMaterial
by setting collider.material
. To make sure that the materials are included in the scene, you can create an array of PhysicMaterials which you set at design time
Make a public array of PhysicMaterials in the class
public PhysicMaterial materials[]
If you fill this list from the inspector in the Unity editor, you can then assign one of the materials at runtime:
collider.material = materials[i]
Answer by Vadelma · Oct 13, 2010 at 09:38 PM
Be careful if you decide to change the properties of a PhysicMaterial object at runtime instead of/without changing the sharedMaterial (or material) property of the colliders using it. In some cases, the physics engine will continue to use the old properties of a PhysicMaterial object. See this forum post of mine for more information.