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:

    Texture2D UpdateThresholdTexture(Texture2D tex)
        Texture2D texture = new Texture2D(tex.width, tex.height);

        for (int y = 0; y < texture.height; y++)
            for (int x = 0; x < texture.width; x++)
                Color color = tex.GetPixel(x, y);

                bool min = color.grayscale >= minThresh;
                bool max = color.grayscale <= maxThresh;

                if (min && max)
                    color.a = 0.8f;
                    texture.SetPixel(x, y, color);
                    color.a = 0f;
                    texture.SetPixel(x, y, color);
        return texture;

At the moment it's just returning the original texture. Could someone point me in the right direction?

  • \$\begingroup\$ Your code does not return the original texture. What symptom leads you to believe that's what it's doing? Are you drawing this texture with a material that uses alpha blending or otherwise makes the alpha change visible? \$\endgroup\$ – DMGregory Jan 27 '20 at 3:20
  • \$\begingroup\$ I'm displaying the texture onto a cube. I'm not sure if that negates the opacity or not? \$\endgroup\$ – doraginuru92 Jan 27 '20 at 3:27
  • \$\begingroup\$ As I said above, it's the material that governs whether alpha is used as opacity, or as some other effect, or ignored entirely. Not the mesh. Show us how you've configured the material that you're using in your cube. \$\endgroup\$ – DMGregory Jan 27 '20 at 10:32
  • \$\begingroup\$ I managed to solve it, ty for the replies though. \$\endgroup\$ – doraginuru92 Jan 27 '20 at 10:39
  • 2
    \$\begingroup\$ If you've solved your problem, please post your solution as an Answer below. \$\endgroup\$ – DMGregory Jan 27 '20 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.