- Home /
How to compare 2 materials?
Similar questions have been asked but none of those solutions seems to work for me.
I want to compare 2 materials to see if they are the same: i.e.
if(material1 == object.renderer.sharedMaterials[0])
{
Debug.Log("Great success!");
}
But this compares false even when I know it to be true. Outputting the name of the shared material shows that it is an instance of the material. How can I get the original in order to compare them?
Not sure if this is your problem, but if you make any changes to your material...color, texture, offset, scale...Unity generates a new material instance. So making this comparison will fail if you are comparing a new instance to the shared material.
Is there any way to compare the instantiated material to the original?
Answer by marjan · Jun 06, 2016 at 12:19 PM
You could compare by name:
Given you have a material in your project called "MyMaterial" it might be on your actual gameObject a "MyMaterial (Instance)". Because you assigned other textures, colors or so.
Now do something like this: String baseMaterialName = myBaseMaterial.name; String assignedMaterialName = myRenderer.sharedMaterial.name;
if (assignedMaterialName.Contains(baseMaterialName) ) { // here is your Match }
Can material names be repeated? If so, and if you're looking for a specific instance, maybe it'd be better to use GetInstanceID() ins$$anonymous$$d.
Answer by andrei-pit · Apr 21, 2020 at 06:33 AM
Comparing sharedMaterial works for me.
Example:
Debug.Log(GameObject.Find("obj1").GetComponent().sharedMaterial == GameObject.Find("obj2").GetComponent().sharedMaterial)
=> returns "False" even if the material names are the same
Is there a way to compare physical materials that you have them as a list and the ones attached to objects without using string compare.