How do I check for a gameobject's material?

In my game I’m trying to check to see if a gameobject is using a certain material.

public Material uDoughMat;
private MeshRenderer pizzaRend;

private void Start() {
    pizzaRend = GetComponent<MeshRenderer>();

private void Update() {
    if (pizzaRend.material == uDoughMat) {
    pizzaType = "Dough";
    }
}

For whatever reason, it refuses to run the check on the material. Am I using the wrong method?

For some reason I don’t know, Unity does not like to compare material instances with assigned materials. Instead you can compare the shared material to the assigned material.

if (pizzaRend.sharedMaterial == uDoughMat) {

You could also use bools to check whether your object has the right material assigned.

//Assign the material
pizzaRend.material = uDoughMat;
doughMat = true;
bakedMat = false;

//Check the bools
if (doughMat) //Do whatever
else if (bakedMat) //Do whatever

*Edited to eliminate any confusion.

The docs usually answer all: https://docs.unity3d.com/ScriptReference/Renderer-material.html

Accessing .material will return an instance of the material, thus it’s not the same as the one assigned via the inspector.

So you can just compare the material and the .sharedMaterial for equality.

2 Likes

Awesome thank you so much!