Unity URP自定义Shader支持RenderLayer
前言:
当我们想用一个灯光只对特定的物体造成影响,而不对其余物体造成影响时,我们就需要设置相对应的LightLayer,但是这在URP12.0是存在的,在之后就不存在LightLayer这一功能,URP将其隐藏而改成了RenderLayer。官方Lit很好的处理了RenderLayer的适配,但是对于我们自定义的Shader效果,要使用RenderLayer就需要增加特定的功能。
实现:
RenderLayer功能是处理特定光影响特定事物的,在shader中可以通过GetMeshRenderingLayer获取当前模型的meshrender中的renderlayer,然后和light的layermask进行对比,如果一致则进行灯光操作,如果不一致则不进行灯光操作,代码如下:
uint renderingLayers = GetMeshRenderingLayer();Light main_light = GetMainLight();half render_mask = main_light.layerMask & renderingLayers;half3 main_light_color = render_mask * main_light.color.rgb;
额外光的处理也是一致,举个例子:
#ifdef _ADDITIONAL_LIGHTSuint pixelLightCount = GetAdditionalLightsCount();for (uint lightIndex = 0u; lightIndex < pixelLightCount; lightIndex++){Light light = GetAdditionalLight(lightIndex, i.positionWS.xyz, i.shadowMask);half3 attenuatedLightColor = light.color * light.distanceAttenuation;half3 main_light_color = (light.layerMask & renderingLayers) * attenuatedLightColor;lightColor += LightingLambert(main_light_color, light.direction, i.normalWS);}#endif
结果:
正常情况下,一盏主光
额外加一盏额外光 ,设置为影响使用官方Lit的模型
切换影响使用自定义Shader的模型
对两个模型都影响