Search Unity

Changing alpha of single pixel value?

Discussion in 'Scripting' started by bw92, Jan 27, 2020.

  1. bw92

    bw92

    Joined:
    Apr 17, 2019
    Posts:
    20
    Hey all,

    I'm trying to change the alpha values of a grayscale texture based on some conditions. Essentially if the color value is within some min and max threshold, set the alpha to 0.8, and if it is not within the thresholds, set it to 0 (unable to see) alpha.

    Here's my code so far:
    Code (CSharp):
    1.     Texture2D UpdateThresholdTexture(Texture2D tex)
    2.     {
    3.         Texture2D texture = new Texture2D(tex.width, tex.height);
    4.  
    5.         for (int y = 0; y < texture.height; y++)
    6.         {
    7.             for (int x = 0; x < texture.width; x++)
    8.             {
    9.                 Color color = tex.GetPixel(x, y);
    10.  
    11.                 bool min = color.grayscale >= minThresh;
    12.                 bool max = color.grayscale <= maxThresh;
    13.  
    14.                 if (min && max)
    15.                 {
    16.                     color.a = 0.8f;
    17.                     texture.SetPixel(x, y, color);
    18.                 }
    19.                 else
    20.                 {
    21.                     color.a = 0f;
    22.                     texture.SetPixel(x, y, color);
    23.                 }
    24.             }
    25.         }
    26.         texture.Apply();
    27.         return texture;
    28.     }
    At the moment it's just returning the original texture. Could someone point me in the right direction?
     
    Last edited: Jan 27, 2020
  2. Karrzun

    Karrzun

    Joined:
    Oct 26, 2017
    Posts:
    129
    Where do you set your minThresh and maxThresh values?

    Edit: Also Debug.Log () your Color.grayscale values to see if they match what you're expecting.

    Edit 2: Also make sure, your scene/object is set up properly to allow transparency.
     
    Last edited: Jan 27, 2020
    bw92 likes this.