December 06 2021
By Rubén Torres Bonet
December 06, 2021
In this post, I’ll show you the true cost you’re paying for the “shader variants” that Unity creates by default and how to stop paying for it.
Good news: Unity creates shader variants automatically for you.
Bad news: Unity also creates performance bottlenecks automatically for you:
Jeez. That doesn’t look like a good idea, does it?
Yes, all shader variants are evil… but they’re a necessary evil that make your work 10x easier (at least at the beginning).
Can you imagine having to write by hand each sub shader every time you do any changes to…
No thanks, I’ll pass.
You luckily don’t do so many sub-shaders by hand. Unity does this automatically for you, which is great.
But it is this “automatic step” that is so dangerous… because it makes you unaware of their performance cost.
Let me put it this way: you don’t know all the shaders that you end up using and therefore you don’t know the STEEP price you’re currently paying to use them.
I’m done listing the challenges. Now it’s time to think of solutions.
Here are the two steps you must follow to get rid of this performance robbery:
My friend, let’s see how.
This is a simple but slightly tedious process.
First, activate shader compilation logging in the project settings.
Second, compile and launch your project in your target platform. Play around through your entire game and get the player logs (you were gathering them, right?).
When you open the logs, you’ll find entries that look like this:
Compiled Shader: Universal Render Pipeline/Lit, pass: ForwardLit, stage:pixel, keywords FOG_EXP2 ...
Here’s another example:
You see those?
Those are the shader variants you’re using.
So the question is now… do you need them all?
I bet you don’t, so let’s see how you can NUKE them for good so they don’t steal your performance juice.
To kill shader variants that you don’t want in, you have two approaches:
No matter the route you choose, you work with whitelists or blacklists.
Basically, you tell which shaders you want to keep… or rather kick out. That’s up to you.
Remember the potential cost of ignoring shader variants?
Well, you can get rid of 80% of these costs if you follow the process I outlined in this post.
And it is not as hard as it looks once you’ve gone correctly through it once :)
If you want to experience the process, step by step, plus an in-depth explanation of shader variants, watch lesson #006 in the Unity Performance Taskforce.
This unique lesson is designed to teach you the 20% of what you need to know to rescue 80% of the performance stolen by shader variants.
So if compile times, load times, memory usage, draw calls and GPU cost are metrics that you care about, check out the lesson #006 of the Unity Performance Taskforce and let me know your results!
Ruben (The Gamedev Guru)