How to modify color.alpha in UI Image?

Hi,
is it possible to modify alpha in image?
I tried to write some code but it doesn’t work.

public Image image;

    	void Start () {
    
    		image = GetComponent<Image>;
    
    		image.color.a = 1f;
    	}

Thanks for your help and ideas :slight_smile:

It is impossible to edit r,g,b or a separately by color.a = 1f.
You can assing only whole Vector3 to color property.
So, please use the next code:

   public Image image;
   void Start () 
   {
         image = GetComponent<Image>();
         var tempColor = image.color;
         tempColor.a = 1f;
         image.color = tempColor;
   }

It is also possible to create a new Color using the original image color’s red, green and blue values and the desired alpha value and assign the new Color to the image color:

public Image image;
  void Start () 
  {
        image = GetComponent<Image>();
        image.color = new Color(image.color.r, image.color.g, image.color.b, 1f);
  }

So not sure if this was addressed by folks but keep in mind that alpha must be set in code using a value between 0 and 1. I was trying to set it to a value between 0 and 255 because that appears to be how the color wheel in the inspector did it. Of course the Unity manual shows this to be the case, but I didn’t look there first.

You can using extension method for this:

public static T ChangeAlpha<T>(this T g, float newAlpha)
        where T : Graphic
    {
        var color = g.color;
        color.a = newAlpha;
        g.color = color;
        return g;
    }

And using: Image.ChangeAlpha(0.5f);

Try this solution

// opaque
GetComponent<Image>().color += new Color(0f, 0f, 0f, 1f);
// transparency
GetComponent<Image>().color -= new Color(0f, 0f, 0f, 1f);

Quick Answer

There are 2 main ways to change the alpha in an Image’s color property.

  1. Change the color on assignment. image.color = new Color(image.color.r, image.color.g, image.color.b, 1)
  2. Use a Vector4 and change the w property. Vector4 color = image.color; color.w=1; image.color = color;

I personally prefer the second way much more as it gives you much more flexibility over the RGBA values.

NOTE :

The XYZW in a Vector4coorespond to the RGBA in a Color.

CORRECTIONS :

  • If you are assigning the Image object in Start, then there is little reason to have the Image privacy set to Public. However, since this script is not preserved through scenes, you’re just wasting processing power by assigning the Image in Start.
  • When dealing with float values, you are only required to add f when you assign decimal numbers to them. When adding a whole number such as 0,1,2,3,4… there is no reason to add a Double to Float conversion.