Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How do I check for a gameobject's material?

Discussion in 'Scripting' started by unity_23chasejohnson, Mar 24, 2023.

  1. unity_23chasejohnson

    unity_23chasejohnson

    Joined:
    Nov 16, 2022
    Posts:
    4
    In my game I'm trying to check to see if a gameobject is using a certain material.
    Code (CSharp):
    1. public Material uDoughMat;
    2. private MeshRenderer pizzaRend;
    3.  
    4. private void Start() {
    5.     pizzaRend = GetComponent<MeshRenderer>();
    6.  
    7. private void Update() {
    8.     if (pizzaRend.material == uDoughMat) {
    9.     pizzaType = "Dough";
    10.     }
    11. }
    For whatever reason, it refuses to run the check on the material. Am I using the wrong method?
     
  2. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    490
    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.
    Code (CSharp):
    1. if (pizzaRend.sharedMaterial == uDoughMat) {
    You could also use bools to check whether your object has the right material assigned.
    Code (CSharp):
    1. //Assign the material
    2. pizzaRend.material = uDoughMat;
    3. doughMat = true;
    4. bakedMat = false;
    5.  
    6. //Check the bools
    7. if (doughMat) //Do whatever
    8. else if (bakedMat) //Do whatever
    *Edited to eliminate any confusion.
     
    Last edited: Mar 24, 2023
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,003
    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.
     
    Kurt-Dekker and QuinnWinters like this.
  4. unity_23chasejohnson

    unity_23chasejohnson

    Joined:
    Nov 16, 2022
    Posts:
    4
    Awesome thank you so much!