Last Updated: February 25, 2016
·
4.67K
· khalladay

Precompile Dynamically Loaded Shaders In Unity

If you've loaded GameObjects at runtime in Unity (ie/ from a Resources.LoadAssetAtPath) you may be familiar with the tell tale frame rate hiccup that occurs the first time that object is seen by the camera.

This is because Unity's default behaviour is to postpone the compilation / optimization of a shader loaded at runtime until it appears on screen. If you load a lot of assets this way (ie/ at the beginning of a scene), this behaviour can lead to a lot of dropped frames down the road. Luckily there exists a workaround.

Simply call Shader.WarmupAllShaders() after loading your assets (or at a convenient time for your framerate to drop momentarily) and Unity will compile all of the shaders currently in the scene. It's a simple solution, but it's easy to overlook if you aren't aware that Unity has this functionality.

tldr: Shader.WarmupAllShaders()