Query renderer.materials in prefabs in Editor without changing to instance

I have a menu item Editor script that searches through all prefabs and tells me what prefabs are using a particular material by using the renderer.materials property. However, this has the negative side effect of changing those prefab materials to an instanced version of the material.

As I understand it, renderer.material or renderer.sharedMaterial will only get me the first material on a renderer, which will not tell me if the renderer has my material on it as the second material. Is there a way to query all of the materials on a renderer without this instancing side effect?

Whenever you call Renderer.material or renderer.materials, unity will create copy’s of the Renderer’s material(s) and return these copy’s instead. And when you set it, it will clone the material and use it. This way you can be sure that this Renderer has a unique Material which you can modify without modifying the visual apearance of any other Renderer with the ‘same’ material.

If you want the actual material (which usually resides in the project folder unless you instantiate it from code), you can use Renderer.sharedMaterial and Renderer.sharedMaterials instead.

So in short, use sharedMaterials…

Loop through the materials.

This will print them out…

Renderer rend = go.GetComponent<Renderer>();

foreach (Material mat in rend.sharedMaterials)
{
	Debug.Log(mat);
}