[URP] Optimize Rendering Performance with Shader Variant Prewarming
Solution
Unity 2021.x - Unity 6.3.x
Published 9 days ago
Performance stutters frequently occur during gameplay when new shader variants are encountered for the first time. This happens because developers often confuse build-time compilation with runtime driver preparation, leading to late dispatching of shader microcode that interrupts the main thread.
To eliminate rendering hitches, your project must distinguish between build-time generation and runtime readiness. During the build phase, Unity compiles shader source code into platform-appropriate microcode. However, these binaries must still be loaded and uploaded to the GPU driver at runtime.
Shader warming is the process of manually triggering this driver upload before the shaders are needed for rendering. This is accomplished via the ShaderVariantCollection API. By calling WarmUp on a prepared collection, the overhead of driver translation is moved from the middle of gameplay to a controlled loading screen or the main menu.
To implement effective warming, follow these steps:
- Use the
Shader Variant Collectorin the Editor to record which variants are actually used during a typical gameplay session. - Save the resulting asset as a
ShaderVariantCollectionin your project folder. - Reference this collection in a initialization script or your loading manager.
- Invoke the WarmUp method on the collection instance to dispatch all recorded variants to the GPU.
Additional Tips:
- If you utilize Addressables or Asset Bundles, ensure the
ShaderVariantCollectionis fully loaded into memory before calling WarmUp. - Excessive warming can lead to long initial load times; only include variants that are likely to appear within the first few minutes of gameplay or those with high complexity.
- For Unity 6, check the Shader Graph settings to strip unused keywords, which reduces the total number of variants requiring a WarmUp call.
TL;DR
Shader compilation occurs during the build process to generate platform-specific microcode, whereas shader warming is a runtime process that prepares these variants for immediate GPU execution.
Related Posts Haven't quite found a solution to your problem? We think these posts might help you.
Content inspired by a Unity discussion post.