Unity3D – Game Engine – Get Material Name

Get the material of THIS gameobject.
IMPORTANT: material is not a Component but a class of renderer Component, the correct statement is:

1
2
3
4
...
// GameObject.Component.Class.Property
this.renderer.material.name
...

Create a Cube, assign a material named ‘material0’, assign the script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#pragma strict
 
function Start () {
 
}
 
function OnMouseDown ()
{
        // When you click over the object play audio
        audio.Play();
         
        // Check material
        // NB: il materiale non è un componente ma una classe di renderer!!!!
        var myMaterial = renderer.material;
        Debug.Log(myMaterial); // -> Risulta: material0 (Instance)
         
    if (this.renderer.material.name == "material0 (Instance)") {
        Debug.Log("material0 found!");
    } else {
        Debug.Log("material0 not found!");
    }
}
 
function Update () {
 
}