Search Unity

Does declaring shader variables as uniform have any effect on behaviour or performance?

Discussion in 'Shaders' started by PsyDev, May 9, 2017.

  1. PsyDev

    PsyDev

    Joined:
    Sep 30, 2015
    Posts:
    31
    You can declare any variable in a shader and set it from cpu code without adding the uniform keyword.

    In Shader:
    float _MyValue;

    In C#:
    myMaterial.SetFloat("_MyValue", 12.34f);

    Does declaring _MyValue as uniform have any effect?
    What does this do?
    uniform float _MyValue

    The docs say you can use it, but it's not necessary. Why do people use it?
     
    SamFernGamer4k likes this.
  2. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    From the HLSL documentation:
    "Uniform data can be specified by two methods. The most common method is to declare global variables and use them within a shader. Any use of global variables within a shader will result in adding that variable to the list of uniform variables required by that shader. The second method is to mark an input parameter of the top-level shader function as uniform. This marking specifies that the given variable should be added to the list of uniform variables."

    So a global variable is uniform (the same for every vertex or pixel) by default. If you supply it as a variable in the method, you have to explicitly set it to uniform. (But this is generally never used, because global variables are easier to read.)

    Code (csharp):
    1.  
    2. // float4 myOffset; // Not needed as global variable, directly in the method signature
    3.  
    4. float4 vert(float4 v:POSITION, uniform float4 myOffset) : SV_POSITION {
    5.    return mul (UNITY_MATRIX_MVP, v) + myOffset;
    6. }
    7.  
     
  3. PsyDev

    PsyDev

    Joined:
    Sep 30, 2015
    Posts:
    31
    Thanks for the reply. So specifying uniform on a global variables is not needed. I wonder why I see so many examples do it then? Maybe people use it as a convention to differentiate between globals that are set by the CPU and globals that are only local to the shader? I dunno.
     
  4. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,546
    They do it because it's safer in the long term and more maintainable. Maybe down the line Unity might change up their compiling so that they are not uniform by default, then a bunch of your shaders might need updating. It's also about creating descriptive code. Just like why it's recommended to use "private" on variables in C# you want to be private even though they are generally private by default, it signals your intent that you truly wish for this to be private and anybody touching your code in the future knows so.