Emission at run time works in Editor, but not in build

I’m setting the Emission in the Standard Shader at runtime and it works perfectly as expected in the editor when I hit play. Unfortunately the exact same code doesn’t work when I build the player.

Emission in Editor:

46679-5-19-2015-10-06-50-am.png

Emission in Build:

Here is the code I’m using to change the emission at run time:

foreach (Transform obj in Xforms)
{
	if (obj.GetComponent<MeshRenderer>() != null)
	{
		foreach (Material mat in obj.GetComponent<MeshRenderer>().materials)
		{
			if (mat.mainTexture != null)
			{
				if (mat.HasProperty("_EmissionMap"))
				{
					if (mat.GetTexture("_EmissionMap") != null)
					{
						float randNum = Random.Range(0f, 1f);
						mat.EnableKeyword("_EMISSION");
						if (randNum < .2)
						{
							mat.SetColor("_EmissionColor", new Color(0f, 0f, 0f, 0f));
						}
						else
						{
							float randColor = Random.Range(.8f, 1f);
							mat.SetColor("_EmissionColor", new Color(1f, 1f, randColor, 1f) * 1.5f);
						}
					}
				}
			}
		}
		DynamicGI.UpdateMaterials(obj.GetComponent<MeshRenderer>());
	}
}
DynamicGI.UpdateEnvironment();

Ideas? :slight_smile:

A colleague of mine has just discovered the reason for this behaviour. Unity internally uses various different shader variants and by default, _EMISSION is not used/compiled. When you set this in runtime, the editor will compile the respective shader variant on the fly, so you see your emission there.

When you build a standalone player however, Unity will only compile the shaders that are referenced by objects in your scene. So in case you don’t already have emissive materials in your scene (not set at runtime), your code will call for a shader that hasn’t been compiled.

This should usually be circumvented through the use of ShaderVariantCollection, but that did not work in our case. What we did was to add a simple cube to the scene with an emissive material. This caused the compiler to deliver the needed shader for the standalone player.

Got it working with ShaderVariantCollection by manually including one of the Standard shader variants which uses the _emission keyword.
82968-emission-fix.png

I solved this issue by enabling the Emission in the Shader Material and setting the default color to something very low.

This code of the .mat:

- _EmissionColor: {r: 0, g: 0, b: 0.004, a: 1}