Hi everyone,
I have a Unity script that changes the emission color of a material at runtime. It works perfectly in the Editor, but after building the project to a Windows EXE, the color changes no longer appear.
Here’s the relevant code:
public void SetEmissionColor(Color baseColor, float intensity)
{
var rend = GetComponent<Renderer>();
if (rend == null) return;
Material mat = rend.material;
mat.EnableKeyword("_EMISSION");
Color scaledColor = baseColor * intensity;
mat.SetColor("_EmissionColor", scaledColor);
}
I’m using Universal Render Pipeline/Lit
Does anyone know how to fix this?
Sounds like you wrote a bug… but before you can fix it, you have to find it… and that means… time to start debugging!
Look in the runtime device logs (google for how)… are there any complaints at startup about shader issues? What about errors during running?
Then move on: is any of the code above even running? Don’t assume it is. What about if you change another property besides _EMISSION? Does it change?
By debugging you can find out exactly what your program is doing so you can fix it.
Use the above techniques to get the information you need in order to reason about what the problem is.
You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.
Once you understand what the problem is, you may begin to reason about a solution to the problem.
Remember with Unity the code is only a tiny fraction of the problem space. Everything asset- and scene- wise must also be set up correctly to match the associated code and its assumptions.
Thanks for the suggestions! I’ve done some debugging and confirmed that the code is being executed—I added Debug.Log statements and they show up in both Editor and EXE.
Interestingly, if I change another property, like _BaseColor, it works perfectly and the color updates are visible. So it seems the issue is specifically with _EmissionColor in the built EXE. Everything else behaves as expected.
I figured out the issue!
The problem wasn’t the code at all. The Emission checkbox in the Material Inspector must be enabled beforehand. If the Emission is disabled in the Inspector, the script cannot turn it on programmatically.
The solution is:
- Open your material in the Inspector.
- Enable the Emission checkbox.
- Set the emission color to black if you don’t want it to glow initially.
After that, your script can safely change _EmissionColor at runtime, and everything works as expected.
Yes. I also found this out the hard way. From what i understand, when you check the “emission” box, then Unity compiles a whole other shader varient for that shader. I think that it does not work at runtime bacause I dont think a Unity build can compile shaders. The editor can compile shaders at run time though, just so you can get to play mode faster.
Thanks for documenting your solution. It will be helpful for anyone who runs into the same issue and googles for it. 