Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Convert images to black-and-white format with alpha channel

Discussion in 'Shaders' started by litvinovandrey, Oct 14, 2015.

  1. litvinovandrey

    litvinovandrey

    Joined:
    Aug 21, 2015
    Posts:
    14
    Hello, my shader is not working properly with an alpha channel, what went wrong?
    Code (CSharp):
    1. Shader "Custom/BWDiffuse" {
    2.     Properties{
    3.         _MainTex("Base (RGB)", 2D) = "white" {}
    4.         _bwBlend("Blend", Range(0, 1)) = 0
    5.     }
    6.         SubShader{
    7.         Pass{ Blend SrcAlpha OneMinusSrcAlpha
    8.         CGPROGRAM
    9. #pragma vertex vert_img
    10. #pragma fragment frag
    11.  
    12. #include "UnityCG.cginc"
    13.  
    14.         uniform sampler2D _MainTex;
    15.     uniform float _bwBlend;
    16.  
    17.     float4 frag(v2f_img i) : COLOR{
    18.         float4 c = tex2D(_MainTex, i.uv);
    19.  
    20.         float lum = c.r*.3 + c.g*.59 + c.b*.11;
    21.         float3 bw = float3(lum, lum, lum);
    22.  
    23.         float4 result = c;
    24.         result.rgb = lerp(c.rgb, bw, 1 - _bwBlend);
    25.         return result;
    26.     }
    27.         ENDCG
    28.     }
    29.     }
    30. }
     
  2. alienheretic

    alienheretic

    Joined:
    Oct 15, 2008
    Posts:
    60
    why not just use float3 bw =Luminance(c.rgb);?
     
  3. litvinovandrey

    litvinovandrey

    Joined:
    Aug 21, 2015
    Posts:
    14
    This don't significantly, the result does not change.
     
  4. litvinovandrey

    litvinovandrey

    Joined:
    Aug 21, 2015
    Posts:
    14
    adding test scene, showing the bug.
     

    Attached Files:

  5. karp505

    karp505

    Joined:
    Jul 24, 2014
    Posts:
    18
    You need to tell the shader not to write to the depth buffer by using ZWrite Off. You should also set some tags, like "Queue"="Transparent", "RenderType"="Transparent", and "IgnoreProjector"="True". Check it out here: http://docs.unity3d.com/Manual/SL-SubShaderTags.html

    Here's your shader back. This works in your test scene.
     

    Attached Files:

    litvinovandrey likes this.
  6. litvinovandrey

    litvinovandrey

    Joined:
    Aug 21, 2015
    Posts:
    14