Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Custom Surface Shader with Alpha

Discussion in 'General Graphics' started by rengle820, Oct 19, 2018.

  1. rengle820

    rengle820

    Joined:
    May 15, 2016
    Posts:
    6
    I've been trying to write a simple custom surface shader that lets me place a hole in my mesh for where the hole is on a golf green, and it's working as expected, except when I enable alpha in the pragma line I get some weird artifacts. It looks like some of my triangles are being rendered before triangles in front and I'm not sure why.


    Code (CSharp):
    1.  Shader "Example/Diffuse Texture" {
    2.     Properties {
    3.       _MainTex ("Main", 2D) = "white" {}
    4.     }
    5.     SubShader {
    6.       Tags { "RenderType" = "Transparent" "Queue" = "Transparent" }  
    7.       CGPROGRAM
    8.       #pragma surface surf Standard fullforwardshadows alpha
    9.       #pragma target 3.0
    10.       struct Input {
    11.           float2 uv_MainTex;
    12.       };
    13.       sampler2D _MainTex;
    14.  
    15.       void surf (Input IN, inout SurfaceOutputStandard o) {
    16.               o.Albedo = tex2D(_MainTex, IN.uv_MainTex).rgb;    
    17.           o.Alpha = 1.0;
    18.       }
    19.       ENDCG
    20.     }
    21.     Fallback "Diffuse"
    22.   }
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    It’s possible that is exactly what’s happening. When using the alpha parameter for surface shaders, ZWrite is disabled on the shader. That means the depth buffer is no longer helping to sort, and the order of the triangles being rendered is all that matters. However it also kind of looks like z fighting. From that picture alone I certainly couldn’t tell you exactly what is happening, but I can say generally speaking you do not want to have larger areas of otherwise opaque surfaces use a transparent shader. If you want to use alpha blending, it’s best to keep the transparent material localized to the few polygons just the area around the hole rather than the entire mesh. This is really true even for alpha tested materials for performance reasons, though you can often get away without it.