Search Unity

Changing PhysicMaterial at runtime

Discussion in 'Scripting' started by KeiranKoz, May 3, 2018.

  1. KeiranKoz

    KeiranKoz

    Joined:
    May 27, 2017
    Posts:
    13
    Hi guys,

    Thanks for reading my post. I'm hoping for help on how to swap the PhysicMaterial on a Terrain at runtime.

    Current test implementation:

    Code (CSharp):
    1. public Terrain terrain;
    2.  
    3. void Update()
    4. {
    5. if(Input.getKeyDown(KeyCode.K))
    6. {
    7. terrain.collider.GetComponent<PhysicMaterial>() = "Oily";
    8. print("Changed to Oily");
    9. }
    10. }
    I'm getting an obvious error, "the left-hand side of an assignment must be a variable, property, or indexer" but I really have no idea how else this could be implemented.

    Help pls?
     
  2. KeiranKoz

    KeiranKoz

    Joined:
    May 27, 2017
    Posts:
    13
    I've also tried this implementation but it gives me a debug log message of "There is no PhysicMaterial" attached to the "Terrain" game object." But I've doublechecked and there certainly is.

    Code (CSharp):
    1. if (Input.GetKeyDown (KeyCode.K))
    2.         {
    3.             {
    4.                 //terrain.collider.GetComponent<PhysicMaterial>() = ("Oily");
    5.                 terrain.GetComponent<Collider>().GetComponent<PhysicMaterial>().name = ("Oily");
    6.                 print ("Changed to Oily");
    7.             }
    8.         }
     
  3. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Try looking at this page / example: https://docs.unity3d.com/ScriptReference/Collider-material.html

    In that example, they modify properties of the material. You could just as well assign to the material itself. You could create a variable for the material(s) in the script, and assign them in the editor to swap between when needed in your code.