0
0
Unityframework~8 mins

Custom shader fundamentals in Unity - Performance & Optimization

Choose your learning style9 modes available
Performance: Custom shader fundamentals
MEDIUM IMPACT
This affects the rendering speed and frame rate by controlling how graphics are drawn on the screen.
Creating a simple color shader for a 3D object
Unity
Shader "Custom/GoodColor" {
  SubShader {
    Pass {
      CGPROGRAM
      #pragma vertex vert
      #pragma fragment frag
      struct appdata { float4 vertex : POSITION; };
      struct v2f { float4 pos : SV_POSITION; };
      v2f vert(appdata v) { v2f o; o.pos = UnityObjectToClipPos(v.vertex); return o; }
      half4 frag(v2f i) : SV_Target { return half4(1, 0, 0, 1); }
      ENDCG
    }
  }
}
Uses half precision for color to reduce GPU load and improves performance on many objects.
📈 Performance GainReduces GPU calculations by about 30% for color output; improves frame rate.
Creating a simple color shader for a 3D object
Unity
Shader "Custom/BadColor" {
  SubShader {
    Pass {
      CGPROGRAM
      #pragma vertex vert
      #pragma fragment frag
      struct appdata { float4 vertex : POSITION; };
      struct v2f { float4 pos : SV_POSITION; };
      v2f vert(appdata v) { v2f o; o.pos = UnityObjectToClipPos(v.vertex); return o; }
      fixed4 frag(v2f i) : SV_Target { return fixed4(1, 0, 0, 1); }
      ENDCG
    }
  }
}
The shader uses fixed4 color directly without optimization and lacks precision control.
📉 Performance CostAdds unnecessary GPU calculations for simple color; can reduce frame rate on many objects.
Performance Comparison
PatternGPU LoadFragment Shader CostMemory UsageVerdict
High precision color and lightingHighHighModerate[X] Bad
Using half precision and simple mathLowLowLow[OK] Good
Rendering Pipeline
Custom shaders run on the GPU during the rendering pipeline stages: vertex processing, fragment processing, and output merging.
Vertex Shader
Fragment Shader
Rasterization
⚠️ BottleneckFragment Shader stage is most expensive due to per-pixel calculations.
Optimization Tips
1Use half precision instead of full float where possible.
2Minimize complex math in fragment shaders.
3Avoid unnecessary calculations inside shaders.
Performance Quiz - 3 Questions
Test your performance knowledge
Which shader precision type generally improves GPU performance?
Ahalf precision
Bfixed precision
Cdouble precision
Dfull float precision
DevTools: Unity Profiler
How to check: Open Unity Profiler, select GPU module, run scene with shader, observe GPU time spent on shader passes.
What to look for: Look for high GPU time in fragment shader stage indicating expensive shader calculations.