- Home /
How to Change transparency of button image in Unity 5.0?
Hi, I would like to change the transparency of button image from the script (written in C#). What is the best way to do it?
Answer by Okido · Apr 22, 2015 at 04:46 PM
Select your Canvas (or a child object of it if you like), in the inspector click Add Component > Layout > Canvas Group.
The Canvas Group component has an alpha property (1 is completely opaque, 0 is completely transparent), which affects this object and any children of it.
In your script, you can store the Canvas Group as a variable with something like this:
CanvasGroup yourNameHere = GetComponent<CanvasGroup>(); //(assuming the script is attached to the same game object as the Canvas Group)
yourNameHere.alpha = 0;
Edit: If you want to fade it out, you can make this Coroutine and call it whenever you need:
IEnumerator Fade (){
while(yourNameHere.alpha > 0){ //use "< 1" when fading in
yourNameHere.alpha -= Time.deltaTime/1; //fades out over 1 second. change to += to fade in
yield return null;
}
}
Well, some n00bish question) why do you put "/1" in "yourNameHere.alpha -= Time.deltaTime/1;"?
The 1 is for the duration of the fade, and the Time.deltaTime makes the fade duration take place in seconds rather than frames. You can read a bit more about it in the Unity API (they multiply in their example, though dividing has been working for me too :))
Answer by DiegoSLTS · Aug 30, 2015 at 04:46 PM
You don't need to add a Canvas Group component to change the alpha of a single image, Canvas Group changes the alpha of the game object with the component and any child on it.
If you have an UI Image you can change the alpha of it by changing the alpha component of the color of that Image.
Just write a script to store a reference of the Image of the UI Button, then in the script change the alpha. Something like this:
public Image ButtonBackground;
public SetTransparency(float transparency) { //transparency is a value in the [0,1] range
Color color = ButtonBackground.color;
color.a = transparency;
ButtonBackground.color = color;
}
Button also has Text as a child and if you only change alpha of the image, text will stay visible. Because of this I think that Canvas Group is better solution.
Answer by EDevJogos · Jun 29, 2016 at 05:28 PM
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);
Can we use coroutine while using extension to fade? If do how? Thanks alot