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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Alpha channel masking in texture

Discussion in 'Scripting' started by rrh, Dec 21, 2016.

  1. rrh

    rrh

    Joined:
    Jul 12, 2012
    Posts:
    331
    Suppose I'm doing a specialized kind of screen-capture, where I've managed to get two rendertextures. One has an alpha channel exactly like I want, but the lighting is wrong. The other has the lighting I want, but no transparency.

    So is there a way to copy the RGB channels from one and the Alpha channel from the other into one texture?

    This is for screen-capture exporting to a PNG, not for rendering in the engine, so I don't particularly need a real-time display to the screen. Though I see there's a Graphics.Blit that can be passed a material, so maybe the way is create a material that applies one texture as a mask of the other?
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    You can create a material shader that takes two texture parameters and combines the channels however you like.

    In a vert/frag shader, you could have a frag method like this:
    Code (CSharp):
    1. sampler2D _MainTex;
    2. sampler2D _AlphaTex;
    3. fixed4 frag(v2f IN) : SV_Target
    4. {
    5.     fixed4 c = tex2D(_MainTex, IN.texcoord);
    6.     float a = tex2D(_AlphaTex, IN.texcoord).a;
    7.     // one of these should work, not sure which (maybe both? can't hurt)
    8.     c.rgb *= a;
    9.     c.a = a;
    10.     return c;
    11. }
    with a properties block like this:
    Code (CSharp):
    1. Properties
    2. {
    3.     [PerRendererData] _MainTex("Color Texture", 2D) = "white" {}
    4.     [PerRendererData] _AlphaTex ("Alpha Mask", 2D) = "white" {}
    5. }
    Whatever that material is applied to will be drawn as a composite of the two textures.

    I'm not an expert so there may be better ways. What you're talking about is absolutely possible tho.
     
  3. rrh

    rrh

    Joined:
    Jul 12, 2012
    Posts:
    331
    So if I use the Graphics.Blit with a material that uses this shader, I should be able to get the result into a final texture?
     
  4. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    Yes I believe the destination texture parameter using the Blit function will do just that.