How do I fix this issue with shaders compiling for every unit (2D RTS)?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Programerer

I’m making a 2D RTS with around a hundred units on screen. I’ve written a shader that gives them team colors and a couple other effects. The problem is that whenever a unit appears on screen for the first time the game lags for a split second. This is probably because Godot is compiling the shader for that unit. Once all the units are on screen there is no more lag, however with 100+ units it creates a real problem.

The lag goes away if I uncheck “local to scene” in shader resources however then I can’t set the units to different colors and so on. For example I set the color for one unit to red using set_shader_param and then all of the units turn red instead of just the one I want.

There must be some way to not have the input uniforms be shared without compiling the shader 100 times. Is there a better way to do this?

:bust_in_silhouette: Reply From: Programerer

Someone helped me and I got it working. The secret is that the material (make unique) should have “local to scene” checked while the shader within the material should have “local to scene” unchecked. This results in the shader being compiled once and reused while the shader parameters stored in the material can be adjusted independently.