how to get shader name in edit mode

I’m working on an editor script that will allow me to find objects that have a particular shader attached to them. Problem is, when I check the name of the shader a material is using with :

if(g.renderer.material.shader.name == shaderName)

I get the error:

Instantiating material due to calling renderer.material during edit mode. This will leak materials into the scene. You most likely want to use renderer.sharedMaterial instead.

Is there another way to do this?

Not to be funny, but have you tried using renderer.sharedMaterial instead? Again, not to be funny, but the 1st two sentences really do explain the problem.

It would be funny, if sharedMaterial didn't throw the same error. Either way, they clear the second time I run the script. I just want to know why this happens.

2 Answers

2

Try with this. it is printing “Diffuse”.

using UnityEngine;
using System.Collections;

public class Shader_find : MonoBehaviour {
void Start () {
if(renderer.material.shader.name==“Diffuse”)Debug.Log (“Diffuse”);
}
}

The error has to do with the complicated way Unity handles materials (which is a semi-standard computer trick.) Materials are often shared by several objects. So, whenever you even look at a material, Unity assumes you want a personal copy of it. It secretly creates one for you. In edit mode, this makes no sense. The error says to write sharedMaterial for the "real" version in Assets.

Ok, so the reason the error clears on the second run is that Unity created a copy of the material on the first run. I'm assuming these copies are destroyed once the game is run.

There are threads on this, but the extra materials clear when they game stops running (or changes scenes while running.) So they never clear in editor scripts, thus the message against using Material.

So the danger is that I might fill the scene up with basically garbage materials. I tried adding a Resources.UnloadUnusedAssets(), but that seemed to do nothing. If I go into and out of playmode the editor script throws the errors again, so could I assume that simply cycling through playmode is enough to clear these extra materials out of the scene? What would the effect of these materials be on a compiled game? Information on this topic seems to be scarce at best, so thanks for all your help.

"leak materials" is the technical term for making extra, possibly constantly growing, garbage. The only danger is probably that editMode may run out of memory and crash. "unity leak materials" gave some knowledgeable-looking results.

In case some case someone still wonder what’s the names (for scripting)in the new standard physic-based shader that comes with Unity 5.x, there’s a list with a visual reference :


The Green texts are float values (either Float, Float3 or Float4 as specified)
The Blue texts are the Texture2D so the actual maps you import in Unity.