Changing a (new) UI Image's alpha value

Hi, I am new to Unity.

I have 3 images on my UI that are set at 0.5 alpha. When the player collects a collectable in the game, I would like one of the images to turn to full alpha, then the same for collectable 2 and so on…

I’m sure it’s a easy process, but I just can’t seem to work it out.

Help would be very much appreciated.

Thanks.

1 Like

Be sure to check the documentation before asking here! You’ll get your answers much quicker :slight_smile:

That being said:

using UnityEngine.UI;

public class Example : MonoBehaviour {
    Image image;

    void Start() {
        image = GetComponent<Image>();
        image.color = Color.white; //or whatever color
    }

}
2 Likes

Wouldn’t it be better to actually set the alpha, instead of changing color?

using UnityEngine.UI;
public class Example : MonoBehaviour {
    Image image;
    void Start() {
        image = GetComponent<Image>();

        Color c = image.color;
        c.a = 0;
        image.color = c;
    }
}
17 Likes

Thanks for the replies. PGJ, yours was exactly what I wanted, cheers!

You can create an extension, so that you can use anywhere on your code:

public static class Extensions
{
    public static void SetTransparency(this UnityEngine.UI.Image p_image, float p_transparency)
    {
        if (p_image != null)
        {
            UnityEngine.Color __alpha = p_image.color;
            __alpha.a = p_transparency;
            p_image.color = __alpha;
        }
    }
}

Then you can just call this from anywhere:

button.GetComponent<Image>().SetTransparency(float value);
13 Likes

What version of unity is this?

1 Like

Why doesn’t this work for setting the alpha? My health bars are constantly 255 alpha. They do change to the correct colors though.

  private void UpdateHpImage()
  {
    var percentHP = (float)Data.CurrentHP / Data.MaxHP;
    hpImage.fillAmount = percentHP;
    if(percentHP == 1)
    {
      hpImage.gameObject.SetActive(false);
    }
    else
    {
      hpImage.gameObject.SetActive(true);
    }
    if(percentHP > .5f)
    {
      hpImage.color = new Color(0, 255, 0, 45);
    }
    else if(percentHP <= .5f && percentHP > .25f)
    {
      hpImage.color = new Color(255, 255, 0, 45);
    }
    else if(percentHP <= .25f)
    {
      hpImage.color = new Color(255, 0, 0, 45);
    }
  }

I guess The a in color for some reason is a float between 0 and 1 for transparency.

@CrimOudin

Besides necro’ing 2 year old thread… Old internet wisdom - RTFM (read that funky manual) - it is explained in the first two lines of description:

Color values go from 0-1.

But there is also Color32 if you want to use 0-255 value range: