Search Unity

Can you have conditionals outside of the CGPROGRAM?

Discussion in 'Shaders' started by AdamBL, Jun 11, 2018.

  1. AdamBL

    AdamBL

    Joined:
    Oct 27, 2016
    Posts:
    29
    I'm working on a shader, and I want to have the option to toggle between two modes (basically show the object or not). Normally I want the object to be hidden, but for debugging purposes sometimes I want to be able to make it visible. To hide it, I have the line

    Code (CSharp):
    1. colormask 0
    and when I want to debug, I just comment it out. However I was thinking it'd be easier if there was a way I could toggle it off and on in the editor.

    I know you can present the user with a toggle using
    Code (CSharp):
    1. [MaterialToggle]
    however I'm not sure how you check it outside of the CGPROGRAM part of the shader.

    Does anyone know how to do that?
     
  2. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,550
    Use an Enum instead like Unity does for their shaders, then you could wrap all your Subshaders in a Category, and put the ColorMask line at the start, this line would get included in all contained subshaders/passes.

    Code (CSharp):
    1. Properties
    2. {
    3.     _MainTex ("Texture", 2D) = "white" {}
    4.         [Enum(None,0,Alpha,1,Blue,2,Green,4,Red,8,All,15)]
    5.     _ColorMask("Color Mask", Int) = 15
    6. }
    7.  
    8. Category
    9. {
    10.     ColorMask [_ColorMask]
    11.  
    12.     SubShader
    13.     {
    14.         Tags { "RenderType"="Opaque" }
    15.         Pass
    16.         {
    17.             /// Pass 1
    18.         }
    19.         Pass
    20.         {
    21.             /// Pass 2
    22.         }
    23.     }
    24. }
    Then you'll have a nifty drop-down on your material to set the ColorMask for all your passes to whatever mode you want for debugging.

    Unity materials can't generate an enum with more than 7 options sadly, so if you want to use certain combined color colormasks, like RG, RB, BG, RGA, RBA, BGA, then you'll have room for one more of those in that Enum, and you'll have to swap out others the enum for combinations you want. The number value for a combination is simply the addition for the singular values. So, BG = 2 + 4 = 6. BGA = 2+4+1 = 7.
     
    Last edited: Jun 11, 2018
  3. AdamBL

    AdamBL

    Joined:
    Oct 27, 2016
    Posts:
    29
    That's awesome! I actually shortened it up a bit, getting rid of the RGBA options since I don't care about them, so now it's just a dropdown with two options. Thanks so much!