Working with dynamic materials/shaders in Unity

So I decided to test a standalone build of a Unity project I am working on and encountered a severe performance issue. I was getting about 15 frames per second, which made no sense at all. At first I thought it was to do with some new objects I had just added or too many normal maps or something.

It turns out that the standalone version did not like something I was doing with dynamically created Materials, and was logging thousands of lines a second to theĀ output_log.txt file. This was the error in the log:

 

NullReferenceException

at (wrapper managed-to-native) UnityEngine.Material:Internal_CreateWithShader (UnityEngine.Material,UnityEngine.Shader) at UnityEngine.Material..ctor (UnityEngine.Shader shader) [0x00000] in <filename unknown>:0 at ParentClassName.Start () [0x00000] in <filename unknown>:0 at ChildClassName.Start () [0x00000] in <filename unknown>:0

(Filename: Line: -1)

 

I immediately suspected I was doing something wrong with the abstract class (ParentClassName), but after some investigation found that no, in fact, it was the Material. This line, specifically:

myHighlightMaterial = new Material(Shader.Find("Reflective/Specular"));

 

To work around it, I simply had a create a new Material in the editor (left blank/default) of the same type (Reflective/Specular), and stick it in the Resources folder. The code to do the same customization is as follows, and works fine.

myHighlightMaterial = Resources.Load("MyHighlightMaterial") as Material;

 

You can also customize the Material using the shader variables all you like, allowing for some neat things, I think.

// Set some material properties
myHighlightMaterial.SetTexture("_Cube", highlightCubemap);
myHighlightMaterial.SetColor("_ReflectColor", myHighlightColor);
myHighlightMaterial.SetColor("_SpecColor", myHighlightColor);
myHighlightMaterial.SetColor("_Color", Color.white);
myHighlightMaterial.SetFloat("_Shininess", 0.01f);

I am back to 60+ frames per second, and no longer sweating. A good bit of positiveĀ reinforcement to occasionally test standalone builds though! Not everything works the same outside the editor.

 

This entry was posted in Unity. Bookmark the permalink.