Compiling shader variants on the fly at runtime

I have a very large shader with a large amount of variants (we have 30+ keywords). This is for a runtime app where the end user has full control over the shader. Meaning all keywords/variants need to be available to the end user. Thus making variant stripping very difficult since we don’t really know which variants will be needed by the end user. And yes all 30 keywords are needed at runtime. We would be looking at billions of variants.

The best solution would be able to compile a variant on the fly only when needed at runtime. Similar to how the Unity editor handles variants. A small delay during compilation is fine. Is there a way to achieve this?

We have tried doing this using a ShaderVariantCollection with not luck. Here is the code

 var keywords = material.shaderKeywords;
 ShaderVariantCollection variants = new ShaderVariantCollection();
 ShaderVariant variant = new ShaderVariant
 {
     shader = material.shader,
     passType = PassType.Normal, // Adjust this as needed
     keywords = keywords
 };

 // Add the variant to the collection
 variants.Add(variant);

 variants.WarmUp();```

There is no way to compile variants at runtime outside of the Editor.
You can try reducing the number of variants compiled by converting some directives into #pragma dynamic_branch, but this may introduce a runtime performance cost.

1 Like