- Home /
How to change alpha channel of ui image?
Why can't I change the alpha channel of my button image using this line of code:
button.image.color.a = 0.5f;
I am getting this error:
error CS1612: Cannot modify a value type return value of `UnityEngine.UI.Graphic.color'. Consider storing the value in a temporary variable
Answer by Superrodan · Jan 28, 2015 at 11:15 PM
You can't change an individual color value directly I can't explain why but I can tell you how to fix it.
Color temp = button.image.color;
temp.a=0.5f;
button.image.color = temp;
You have to do this with all types of data that are made up of smaller types of data.
So, for example, any variable that uses a Vector3, like position or rotation would be handled the same way. First you store the variable in a temporary holder and then modify one part of the holder. Then you set your object to be equal to that holder.
If you wanted to move your object to the right, for example, you would have to do this:
Vector3 tempVector = myObject.transform.localPosition;
tempVector.x+=100;
myObject.transform.localPosition = tempVector;
You'll use this method a LOT when program$$anonymous$$g in Unity, I've found.
Answer by Michio-Magic · May 30, 2015 at 05:20 PM
This worked for me:
var white : UI.Image; //select Image in Canvas
private var fade : float;
private var endlevel : boolean;
function FixedUpdate() {
if (Input.GetKeyDown("f"))endlevel=true; //used to test it
if(endlevel){
fade+=0.01f; if(fade>1)fade=1; // from 0.0 to 1.0
white.color.a=fade;
}
}
Answer by MrProcessor · Jun 09, 2020 at 10:03 AM
I made it like this: public Image myImageObject; public Color opaque; public Color transparent; void MakeOpaqe() { myImageObject.GetComponent().color = opaque; } void MakeTransparent() { myImageObject.GetComponent().color = transparent; }
In the editor, I made the opaque and transparent colors as I desired. This was easier for me I hope it helps <3
Make sure you are referencing the Image
component from the UnityEngine.UI
namespace, not an image from another namespace or a custom Image
class.
To avoid any confusion:
private UnityEngine.UI.Image image;
void Update()
{
image = GetComponent<UnityEngine.UI.Image>();
// ....
}
@Hellium thank you. the code does not fail but image's opacity value does not decrease. My code: