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 :)
Answer by Denvery · Jan 04, 2016 at 07:38 PM
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;
}
Could you write the same code in C#? var is something that is used in JS as I remember.
Well, I'm silly I guess :) Then.. could you tell me what "var" means?
And there is an error in your code: "Cannot convert method group GetComponent' to non-delegate type
UnityEngine.UI.Image'. Consider using parentheses to invoke the method "
You have missed brackets in GetComponent<Image>
Right:
GetComponent<Image>()
Answer by WanderRook · May 31, 2018 at 11:54 AM
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);
}
Answer by unity_WXIWcvH1Gzms2A · Dec 22, 2018 at 06:26 AM
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);
Answer by grizzly101 · Jan 02, 2020 at 12:43 PM
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.