Search Unity

Shader working with Sprite Renderer sorting order but not canvas sorting order?

Discussion in 'Shaders' started by HaydarLion, May 1, 2019.

  1. HaydarLion

    HaydarLion

    Joined:
    Sep 17, 2014
    Posts:
    62
    So I have basically no knowledge of shaders, but I managed to frankenstein this together:

    Code (CSharp):
    1. Shader "Custom/UnlitDistortion2" {
    2.     Properties
    3.     {
    4.         _MainTex ("Base (RGB)", 2D) = "white" {}
    5.         _DistortionFrequency ("Distortion frequency", float) = 50
    6.         _DistortionSpeed ("Distortion speed", float) = 1
    7.         _DistortionScale ("Distortion scale", float) = 0.1
    8.     }
    9.     SubShader {
    10.         Tags { "RenderType"="Opaque" }
    11.         LOD 200
    12.        
    13.         //Added to use with 2D Sorting Order
    14.         Tags{"Queue" = "Transparent"}
    15.         Pass{
    16.                ZTest Off
    17.                Blend SrcAlpha OneMinusSrcAlpha
    18.             //your CGPROGRAM here          
    19.         }
    20.  
    21.         CGPROGRAM
    22.         #pragma surface surf NoLighting
    23.  
    24.         sampler2D _MainTex;
    25.         float _DistortionFrequency;
    26.         float _DistortionScale;
    27.         float _DistortionSpeed;
    28.  
    29.         struct Input {
    30.             float2 uv_MainTex;
    31.         };
    32.  
    33.         fixed4 LightingNoLighting(SurfaceOutput s, fixed3 lightDir, fixed atten) {
    34.             fixed4 c;
    35.             c.rgb = s.Albedo;
    36.             c.a = s.Alpha;
    37.             return c;
    38.         }
    39.  
    40.         void surf (Input IN, inout SurfaceOutput o) {
    41.             float x = IN.uv_MainTex.x-0.5; //Technically should multiply by 2 to normalize but it adds more computational cost
    42.             float y = IN.uv_MainTex.y-0.5; //Technically should multiply by 2 to normalize but it adds more computational cost
    43.             float dist = x*x + y*y; //Technically incorrect, you can use sqrt here for correct value but it adds more computational cost "sqrt(x*x + y*y);"
    44.             half4 c = tex2D (_MainTex, IN.uv_MainTex + float2(_DistortionScale,0)*sin((_Time*_DistortionSpeed+dist)*_DistortionFrequency));
    45.             o.Albedo = c.rgb;
    46.             o.Alpha = c.a;
    47.         }
    48.  
    49.        
    50.         ENDCG
    51.     }
    52.     FallBack "Diffuse"
    53. }
    The problem is that I need this shader to work essentially as a sprite in a 2D game, and at the moment, it respects the sorting order for sprites. However, when a UI Canvas is supposed to be drawn over it, the entire sprite with the shader (including any sprites that are being drawn on top of it) appear on top of the canvas. Any ideas how I can fix this?