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

Using color from Image in custom shader

Discussion in 'Shaders' started by shenanigans, Dec 19, 2018.

  1. shenanigans

    shenanigans

    Joined:
    Mar 28, 2014
    Posts:
    4
    Simple little problem here:

    The builtin Image component has a sprite property and a color property inherited from Graphic. It uses these to override the values in the assigned material and prevent you having to create a Material asset for every UI image in your project. Neat!

    The sprite property writes to _MainTex in the shader. The color property writes to.... what? I imagined it would be either _Color or _Tint but it's not! Please somebody tell me it's not pre-tinting my sprite on the CPU...

    So how can I write a shader that works smoothly with the standard Image script? This seems like it should be super simple, right?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,238
    Sprites use the vertex colors of the mesh for color.
     
  3. shenanigans

    shenanigans

    Joined:
    Mar 28, 2014
    Posts:
    4
    *yawn* ok it's writing to vertex color. Which is pretty weird considering the default UI shader has a tint color property.

    Hopefully this makes it into the docs someday.
     
  4. whogas

    whogas

    Joined:
    Oct 18, 2013
    Posts:
    46
  5. BeregAlto

    BeregAlto

    Joined:
    Aug 5, 2018
    Posts:
    14
    Can you please share the shader script? Can't figure that out.
     
  6. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,495
    It writes to the vertex color like bgolus said. So in the shader you're writing, the Input struct to your vertex pass should have a property bound to the COLOR semantic, such as this
    fixed4 color : COLOR;
    .

    Then in your vert() pass you'll be able to access it through
    v.color
    for example (if using
    v
    as the field name as is typical)

    You then can also have the same
    color
    field defined in your v2f (vert to frag) struct and set that color in your vertex program, typically it would look something like
    o.color = v.color;
    .

    Then in your fragment program, you can use this color however you want by accessing it using the input struct reference, which is usually
    i
    or
    IN
    (but this is just a field name, you could define it whatever).

    So lastly, after you sample your sprite, you would multiply that sampled color by the
    IN.color
    for example, resulting in the tint being applied.
     
    thelosev, Arjun-Gupte and ATate like this.