Search Unity

Applying Materials With a script

Discussion in 'Scripting' started by Magicpickle97, Jul 26, 2011.

  1. Magicpickle97

    Magicpickle97

    Joined:
    Feb 19, 2011
    Posts:
    89
    Does anyone know how to write a script that will allow me to apply a material to a mesh when I hit a button or something?
     
  2. CheyTac

    CheyTac

    Joined:
    Feb 17, 2011
    Posts:
    71
  3. bdev

    bdev

    Joined:
    Jan 4, 2011
    Posts:
    656
    To change the material on a mesh renderer:
    Code (csharp):
    1.  
    2. var meshRenderer = componentOrGameObject.GetComponent<MeshRenderer>();
    3. if( meshRenderer )
    4.     meshRenderer.sharedMaterial = newMaterialToChangeTo;
    5.  
    you could also use componentOrGameObject.renderer but if you have a particle renderer or trail renderer as well you might get one of those instead. And you should check if its non null unless your sure.

    using .material instead of .sharedMaterial may make a copy of the material you set as well ( which you may or may not want )