# How can I fade out my overlay in Unity?

Something that I can accomplish in 5 minutes in libGDX is taking me forever in Unity. I have a Canvas with a button that covers my entire screen. When the button is clicked, I want the button to fade out and then for the underlying UI to be clickable (if the button is just faded out but it's still on top, you can't click anything).

I tried to use crossFadeAlpha on the Image attached to the button, but the problem is that crossFadeAlpha is async, so I can't do image.enabled = false; when it finishes.

Is there any simple way to accomplish this task in Unity?

• Honestly, I would get a tween engine like DoTween. Makes things simple. – Draco18s no longer trusts SE Jul 29 '17 at 3:06
• I've tried using a tween engine (iTween and LeanTween). Their documentation is lacking, and I can't find anything online about fading using either of them. – Morgan Usley Jul 29 '17 at 4:02
• Try DoTween. Its is free and pretty easy to use. Syntax isn't what I'm used to (AS3's Tweener library), but I figured it out in about 20 minutes. – Draco18s no longer trusts SE Jul 29 '17 at 5:11
• Guess you can fade the button right ? Why not disable the button when its alpha reaches 0 ? – Thalthanas Jul 29 '17 at 6:41
• @EmreE that's the problem. How do you execute a function when the alpha reaches 0, when crossFadeAlpha is an async operation. – Morgan Usley Jul 29 '17 at 19:46

Using a Tween engine may not be necessary here, a simple coroutines will do the job :

private IEnumerator FadeOut( float duration )
{
Image image = GetComponent<Image>();
Color color = image.color;
float startAlpha = color.alpha;
float endAlpha = 0;

for ( float t = 0 ; t < duration ; t += Time.deltaTime )
{
color.alpha = Mathf.SmoothStep ( startAlpha, endAlpha, t / duration ) ;
image.color = color;
yield return null;
}
color.alpha = endAlpha;
image.color = color;
image.enabled = false;
}

// ....

StartCoroutine ( FadeOut ( 5f ) ) ;


I'm on my phone, I haven't tested and the formatting is bad, sorry.

• There's a slight delay between when the alpha fades to 0 and when the enablement is set to false. Is it possible to execute that transition more seamlessly? – Morgan Usley Jul 30 '17 at 1:03
• Are you sure you run the coroutine only once ? I have forgotten one line in my answer. I have updated it. – Hellium Jul 30 '17 at 10:22

Try the code below. The update method of the button's script:

private float alpha;

void Update(){
//Apply fade process here
if(alpha <= 0){
GetComponent<Button>().enabled = false;
}
}