# 着色器错误：在'Custom/WaterShader'中：无效的子着色器索引5。子着色器数量为3。

- **ID:** `unity/shader-invalid-subshader-index`
- **领域:** unity
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 2021.3 | active | — | — |
| 2022.3 | active | — | — |
| 2023.3 | active | — | — |

## 解决方案

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.
   ```

## 无效尝试

- **** — Adding unused subshaders bloats the shader and may cause compilation issues; the correct fix is to adjust the index, not the shader. (50% 失败率)
- **** — High indices still trigger the same error if they exceed the count; the index must be within range. (80% 失败率)
- **** — Shader.Find returns the shader object, but index 0 may not be the intended subshader for all hardware. (40% 失败率)
