- Home /
Checking Object Material against list of materials
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.
Answer by Tuck · Mar 23, 2011 at 08:04 PM
Alright, so what I ended up doing was using string.split (reference here) to separate the strings of each material name into substrings whenever it encounters the '(' character, and then just compared the names of each material.
i.e. 'testMaterial (UnityEngine.Material)' and 'testMaterial (Instance) (UnityEngine.Material)' both become 'testMaterial ' so I can just compare the split name of the target object against the split name of each object in the list! Not quite as elegant as a simple list.contains() but works just fine :)
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.
Answer by Alexandre Zakime · Mar 23, 2011 at 07:17 PM
You could change the name of the instance.
var myObject = instantiate(prefab, transform.position, Quaternion.identity);
myObject.name = "testMaterial";
Don't know if it works properly
Ha that actually might work with some tweaks. I'd been operating under the assumption that names were Read Only. I'll try it out and post my results.
Hmmm after some messing about that solution seems doable but really messy. I would have to essentially insert the string "(Instance)" in between the name of the material and the auto generated "(UnityEngine.$$anonymous$$aterial)" bit. I'm going to poke around for another solution for a while.
Your answer
![](https://koobas.hobune.stream/wayback/20220613114446im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Setting an object's material causes strange behavior in custom editor 0 Answers
Normal map not rendered until the material asset is selected in the inspector 1 Answer
Making new material instance of sharedMaterial in editor mode 1 Answer
Material.mainTexture not working outside of runtime? 1 Answer
Customizing Editor Interface 1 Answer