I have a list of materials set in an inspector window, and I want to check several objects to see if they are using any of the materials in the list. The code I have currently looks roughly like:
if(materialsList.Contains(targetObject.renderer.sharedMaterial))
doStuff();
However this does not work because the materials attached to the object are of a different instance. For example, if I log the names of a material in the list called 'testMaterial,' and the name of the same material when attached to an object, I get
Debug.Log(materialsList[appropriateIndex].name) //Output is 'testMaterial (UnityEngine.Material)'
Debug.Log(targetObject.renderer.sharedMaterial.name) //Output is 'testMaterial (Instance) (UnityEngine.Material)'
Is there a way for me to show that these two materials are the same? Thanks.
Unfortunately, checking just names is quite error-prone: if you'll have more materials with the same name in your project, you can easily mix them up. A correct solution should be tracking down the source instance and comparing this. Unfortunately I don't know whether this is possible.
– Petr_Benysek