Use the built-in functions in the UNITY autolight.cginc file unity_light_attenuation
Shader as follows:
//Upgrade note:replaced ' Mul (unity_matrix_mvp,*) ' with ' unityobjecttoclippos (*) 'Shader"Custom/forward Rendering"{Properties {_maintex ("Main Texture", 2D) =" White"{} _specular ("Specular", Color) = (1,1,1,1) _gloss ("Gloss", Range (8, the)) =8} subshader {Pass {Tags {"Lightmode"="Forwardbase"} cgprogram#pragmaVertex vert#pragmaFragment Frag#pragmaMulti_compile_fwdbase#include"Unitycg.cginc"#include"Lighting.cginc"#include"Autolight.cginc"sampler2d _maintex; Fixed4 _specular; float_gloss; structAppData {float4 vertex:position; FLOAT2 uv:texcoord0; FLOAT3 Normal:normal; }; structv2f {float4 pos:sv_position; FLOAT2 uv:texcoord0; FLOAT3 Worldnormal:texcoord1; FLOAT4 Worldpos:texcoord2; Shadow_coords (3) }; v2f Vert (AppData v) {v2f o; O.pos=Unityobjecttoclippos (V.vertex); O.uv=V.uv; O.worldnormal=Unityobjecttoworldnormal (V.normal); O.worldpos=Mul (Unity_objecttoworld, V.vertex); Transfer_shadow (o); returno; } fixed4 Frag (v2f i): sv_target {fixed4 albedo=tex2d (_maintex, I.UV); Fixed4 Ambient= Albedo *unity_lightmodel_ambient; FLOAT3 Worldlight=Normalize (Unityworldspacelightdir (i.worldpos.xyz)); FLOAT3 WorldView=Normalize (Unityworldspaceviewdir (i.worldpos.xyz)); FIXED4 diff= Albedo * _LIGHTCOLOR0 * MAX (0, Dot (i.worldnormal, worldlight)); FLOAT3 Halfdir= Normalize (WorldView +worldlight); FIXED4 Spec= Albedo * _specular * POW (max (0, Dot (Halfdir, i.worldnormal)), _gloss); Unity_light_attenuation (Atten, I, i.worldpos.xyz); Fixed4 Col= ambient + (diff + spec) *Atten; returnCol; } ENDCG} Pass {Tags {"Lightmode"="Forwardadd"} Blend One one Cgprogram#pragmaVertex vert#pragmaFragment Frag#pragmaMulti_compile_fwdadd_fullshadows//Add a shadow effect#include"Unitycg.cginc"#include"Lighting.cginc"#include"Autolight.cginc"sampler2d _maintex; Fixed4 _specular; float_gloss; structAppData {float4 vertex:position; FLOAT2 uv:texcoord0; FLOAT3 Normal:normal; }; structv2f {float4 pos:sv_position; FLOAT2 uv:texcoord0; FLOAT3 Worldnormal:texcoord1; FLOAT4 Worldpos:texcoord2; Shadow_coords (3) }; v2f Vert (AppData v) {v2f o; O.pos=Unityobjecttoclippos (V.vertex); O.uv=V.uv; O.worldnormal=Unityobjecttoworldnormal (V.normal); O.worldpos=Mul (Unity_objecttoworld, V.vertex); Transfer_shadow (o); returno; } fixed4 Frag (v2f i): sv_target {fixed4 albedo=tex2d (_maintex, I.UV); FLOAT3 Worldlight=Normalize (Unityworldspacelightdir (i.worldpos.xyz)); FLOAT3 WorldView=Normalize (Unityworldspaceviewdir (i.worldpos.xyz)); FIXED4 diff= Albedo * _LIGHTCOLOR0 * MAX (0, Dot (i.worldnormal, worldlight)); FLOAT3 Halfdir= Normalize (WorldView +worldlight); FIXED4 Spec= Albedo * _specular * POW (max (0, Dot (Halfdir, i.worldnormal)), _gloss); Unity_light_attenuation (Atten, I, i.worldpos.xyz); Fixed4 Col= (diff + spec) *Atten; returnCol; } ENDCG}} Fallback"Vertexlit"}
The effect is as follows:
Unity Shader Learning Shadow, decay unified processing