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. Dismiss Notice

Initial values for variables in CG shader not being set

Discussion in 'Shaders' started by lifeformed, Feb 11, 2013.

  1. lifeformed

    lifeformed

    Joined:
    Aug 1, 2012
    Posts:
    51
    Hey guys, quick question:
    If I declare a variable outside of a function, it doesn't seem to get set to the initial value. What gives?

    Code (csharp):
    1.  
    2. float myVar = 1;
    3. float getVar()
    4. {
    5.      return myVar; // returns 0
    6. }
    7.  
     
  2. Daniel_Brauer

    Daniel_Brauer

    Unity Technologies

    Joined:
    Aug 11, 2006
    Posts:
    3,355
    I assume all variables defined outside functions need to be initialized using Shader.SetFloat() or whatever. Otherwise you can just define a constant.
     
  3. Martin-Kraus

    Martin-Kraus

    Joined:
    Feb 18, 2011
    Posts:
    617
    I might be wrong, but I think it depends on the material: once you have a material associated with a shader, it is the material that specifies the values of all uniform variables - regardless of the values that you specify in the shader. Thus, changing the values in the shader won't change the values in the material.
     
  4. aubergine

    aubergine

    Joined:
    Sep 12, 2009
    Posts:
    2,864
    It might be a bug or not maybe it is the way it was intended im not sure, but if you declare your variable and the value in CGINCLUDE - ENDCG, then you can use it in your functions.
     
  5. Martin-Kraus

    Martin-Kraus

    Joined:
    Feb 18, 2011
    Posts:
    617
    Just tested it. Apparently, I was wrong and the initialization of uniforms doesn't matter at all. (Even if there is no property defined for it; otherwise the property's initialization is applied, except if the material has already a value.)
     
  6. lifeformed

    lifeformed

    Joined:
    Aug 1, 2012
    Posts:
    51
    I ended up just setting it outside of the shader with Shader.SetGlobalFloat. That works for me, although it would've been nice to have some default values to work with.
     
  7. RC-1290

    RC-1290

    Joined:
    Jul 2, 2012
    Posts:
    639
    In Compute shaders (hlsl), the initialization only works when the variable is marked as static. When you do that, the variable also becomes invisible to the application (Perhaps that is why initialization is ignored in other cases, Unity might be overriding it).

    I'm guessing it works similarly for Cg.
     
    FrancM12 likes this.