unity runtime_error ai_generated true

Shader error in 'Custom/WaterShader': Invalid subshader index 5. Subshader count is 3.

ID: unity/shader-invalid-subshader-index

Also available as: JSON · Markdown · 中文
90%Fix Rate
86%Confidence
1Evidence
2024-01-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2021.3 active
2022.3 active
2023.3 active

Root Cause

A script references a subshader index that exceeds the number of subshaders defined in the shader file.

generic

中文

脚本引用的子着色器索引超过了着色器文件中定义的子着色器数量。

Official Documentation

https://docs.unity3d.com/Manual/SL-SubShader.html

Workarounds

  1. 95% success Correct the subshader index in the script. For example, change material.shader = shader; material.SetShaderPassIndex(1); to material.shader = shader; material.SetShaderPassIndex(0); where index 0 is the first subshader.
    Correct the subshader index in the script. For example, change material.shader = shader; material.SetShaderPassIndex(1); to material.shader = shader; material.SetShaderPassIndex(0); where index 0 is the first subshader.
  2. 75% success Add a fallback subshader at the end of the shader file to handle unexpected indices: SubShader { Tags { "RenderType"="Opaque" } Pass { ... } }.
    Add a fallback subshader at the end of the shader file to handle unexpected indices: SubShader { Tags { "RenderType"="Opaque" } Pass { ... } }.
  3. 80% success Use ShaderVariantCollection to precompile only the needed subshaders, avoiding runtime index errors.
    Use ShaderVariantCollection to precompile only the needed subshaders, avoiding runtime index errors.

中文步骤

  1. Correct the subshader index in the script. For example, change material.shader = shader; material.SetShaderPassIndex(1); to material.shader = shader; material.SetShaderPassIndex(0); where index 0 is the first subshader.
  2. Add a fallback subshader at the end of the shader file to handle unexpected indices: SubShader { Tags { "RenderType"="Opaque" } Pass { ... } }.
  3. Use ShaderVariantCollection to precompile only the needed subshaders, avoiding runtime index errors.

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Adding unused subshaders bloats the shader and may cause compilation issues; the correct fix is to adjust the index, not the shader.

  2. 80% fail

    High indices still trigger the same error if they exceed the count; the index must be within range.

  3. 40% fail

    Shader.Find returns the shader object, but index 0 may not be the intended subshader for all hardware.