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
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
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);
There are 2 main ways to change the alpha in an Image’s color property.
image.color = new Color(image.color.r, image.color.g, image.color.b, 1)
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.
The XYZW in a Vector4coorespond to the RGBA in a Color.