Search Unity

Switch between opaque/transparent in custom shader tutorial

Discussion in 'Shaders' started by PocketJoyApps, Mar 18, 2019.

  1. PocketJoyApps

    PocketJoyApps

    Joined:
    Jun 3, 2015
    Posts:
    5
    The built-in standard surface shader can be set to opaque or transparent using the 'Rendering Mode' option, for example see this thread http://answers.unity.com/answers/1265884/view.html

    However, custom shaders can not be changed at run-time by default. Eventually I did figure out a way, but could not find this anywhere online

    1. Use "Tags { "RenderType"="Opaque" }", or whatever default you want, this gets auto-replaced by the code I linked anyways

    2. In your shader, use keepalpha, eg. "#pragma surface surf Standard vertex:vert fullforwardshadows keepalpha"
    This WILL make your shader transparent (even if it's alpha=1, the shader's 'Rendering Mode' is equivalently set to Transparent, so you might notice the depth is ruined (as it should be since it's transparent)

    3. This is the important part. Include "Blend SrcAlpha OneMinusSrcAlpha" after the Tag part. The reason this is the kicker is because keepalpha will otherwise override the blending, which is what causes keepalpha to make explicitly opaque shaders become transparent anyways

    That's it. Please remember this won't add an actual option to the material's UI, it still must be changed through code like this http://answers.unity.com/answers/1265884/view.html
    If you do want to add a custom option to the UI you'll need to figure something out with preprocessor macros (pragma directives/defines) to enable/disable step 3
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    The keepalpha setting will do no such thing. The other alpha and alpha:fade etc. will, and nothing you set on the shader or material will matter because those will override any Blend mode you set. Using keepalpha works explicitly because it does not override the blend state (on the base pass, the add pass is always overridden and there's nothing you can do about that, but that's a good thing).

    * Note: setting a Blend mode on a surface shader with addshadow will override the blend mode on the shadow caster pass too! This may prevent shadows from appearing!