Version: 2020.1
Using materials with C# scripts
Physically Based Rendering Material Validator

Scripting for materials that use the Standard Shader

In the Built-in Render Pipeline, the Standard Shader has some extra requirements if you want to modify materials at runtime.

This is because - behind the scenes - the Standard Shader is actually many different shaders rolled into one. These different types of shader are called Shader Variants and can be thought of as all the different possible combinations of the shader’s features, when activated or not activated.

Por ejemplo, si usted escoge asignar un Normal Map a su material, usted activa esa variant del shader que soporta Normal Mapping. Si usted posteriormente también asigna un Height Map entonces usted activa la variant del shader que soporta Normal Mapping y Height Mapping.

This is a good system, because it means that if you use the Standard Shader, but do not use a Normal Map in a certain material, you are not incurring the performance cost of running the Normal Map shader code - because you are running a variant of the shader with that code omitted. It also means that if you never use a certain feature combination (such as HeightMap & Emissive together), that variant is completely omitted from your build - and in practice you will typically only use a very small number of the possible variants of the Standard Shader.

Unity avoids simply including every possible shader variant in your build, because this would be a very large number, some tens of thousands! This high number is a result not only of each possible combination of features available in the material Inspector, but also there are variants of each feature combination for differing rendering scenarios such as whether or not HDR is being used, lightmaps, GI, fog, etc. Including all of these would cause slow loading, high memory consumption, and increase your build size and build time.

Más bien, Unity le hace seguimiento a qué variants ha utilizado al examinar los assets de material utilizados en su proyecto. Independientemente de las variants del Standard Shader que haya incluido en su proyecto, éstas son las variantes que se incluyen en la construcción.

Esto presenta dos problemas por separado cuando acceda materiales vía script que utilice el Standard Shader.

1. Usted debe habilitar las palabras claves correctas para su Standard Shader variant

If you use scripting to change a material that would cause it to use a different variant of the Standard Shader, you must enable that variant by using the EnableKeyword function. A different variant would be required if you start using a shader feature that was not initially in use by the material. For example assigning a Normal Map to a Material that did not have one, or setting the Emissive level to a value greater than zero, when it was previously zero.

Las palabras claves específicas que se requieren para habilitar las características del Standard Shader son las siguientes:

Palabra clave Característica
_NORMALMAP Normal Mapping
_ALPHATEST_ON “Cut out” Transparency Rendering Mode
_ALPHABLEND_ON “Fade” Transparency Rendering Mode
_ALPHAPREMULTIPLY_ON “Transparent” Transparency Rendering Mode
_EMISSION Emission Colour o Emission Mapping
_PARALLAXMAP Height Mapping
_DETAIL_MULX2 Secondary “Detail” Maps (Albedo & Normal Map)
_METALLICGLOSSMAP Metallic/Smoothness Mapping en Metallic Workflow
_SPECGLOSSMAP Specular/Smoothness Mapping en Specular Workflow

Utilizando las palabras claves de arriba es suficiente para recibir sus modificaciones del Material script mientras trabaje en el editor.

No obstante, ya que Unity solamente revisa por materiales utilizados en su proyecto para determinar qué variants incluir en su construcción, no incluirá variants que solamente se encuentran vía script en tiempo de ejecución.

Esto significa que si usted habilita la palabra clave _PARALLAXMAP para un Material en su script, pero no tiene un Material utilizado en su proyecto que coincida con la misma combinación de características, el parallax mapping no funcionará en la construcción final - incluso si parezca que funcione en el editor. Esto se debe a que la variant será omitida desde la construcción porque parece que no porque no parece ser necesario.

2. Usted debe asegurarse que Unity incluya sus shader variants requeridas en la construcción.

Para hacer esto, usted necesita asegurarse que Unity sepa que usted quiere utilizar esa shader variant al incluir al menos un Material de ese tipo en sus Assets. El material debe ser utilizado en una escena o alternativamente se debe colocar en su carpeta de Resources - de lo contrario Unity lo omitirá de su construcción, porque parece sin utilizar.

Al completar ambos de los pasos de arriba, usted tiene la habilidad completa de modificar sus Materiales utilizando el Standard Shader en tiempo de ejecución.

Si usted está interesado en aprender más acerca de los detalles del shader variants, y cómo escribir sus propios, lea más acerca de Crear varias shader program variants aquí.

Using materials with C# scripts
Physically Based Rendering Material Validator