Monthly Archives: December 2016

Fade your UI In and Out

I’m currently polishing my 3rd game, Mouse Dreams, and I wanted my UI to fade in and out smoothly for a polished look: fadeinout Fading a canvas requires that your canvas has a Canvas Group component: image Look at that first property in the Canvas Group component – Alpha. To fade this canvas you simply modify its Alpha property (alpha = how opaque or transparent something is). I created a simple script with a static FadeCanvas method that will fade between a start and end alpha value (e.g. start at 1 and end at 0 to fade out) over a given duration. To fade out a CanvasGroup from 1 (full alpha) to 0 (fully transparent/invisible) over 2 seconds, you would use the following: [code language=”csharp”]StartCoroutine(FadeEffect.FadeCanvas(myCanvas, 1f, 0f, 2f));[/code]   By setting the start alpha lower than the end alpha, the canvas will fade in. Tip: if you want to wait for the fading to finish before doing something else (e.g. displaying some buttons), you can wait for a coroutine to finish from within another coroutine, for example: [code language=”csharp”] IEnumerator FadeThenShowButtons() { // start fading yield return StartCoroutine(FadeEffect.FadeCanvas(myCanvas, 1f, 0f, 2f)); // code here will run once the fading coroutine has completed myButton.enabled = true; }[/code]   Below is the full code I use in my game. The fading is pretty simplistic, so you could replace that part of the code with something more complex (e.g. start of quickly fading, then slow down towards the end). I’ve heavily commented the code so you can see what it is doing. [code language=”csharp”] using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class FadeEffect : MonoBehaviour { public static IEnumerator FadeCanvas(CanvasGroup canvas, float startAlpha, float endAlpha, float duration) { // keep track of when the fading started, when it should finish, and how long it has been running&lt;/p&gt; &lt;p&gt;&a var startTime = Time.time; var endTime = Time.time + duration; var elapsedTime = 0f; // set the canvas to the start alpha – this ensures that the canvas is ‘reset’ if you fade it multiple times canvas.alpha = startAlpha; // loop repeatedly until the previously calculated end time while (Time.time <= endTime) { elapsedTime = Time.time - startTime; // update the elapsed time var percentage = 1/(duration/elapsedTime); // calculate how far along the timeline we are if (startAlpha > endAlpha) // if we are fading out/down { canvas.alpha = startAlpha - percentage; // calculate the new alpha } else // if we are fading in/up { canvas.alpha = startAlpha + percentage; // calculate the new alpha } yield return new WaitForEndOfFrame(); // wait for the next frame before continuing the loop } canvas.alpha = endAlpha; // force the alpha to the end alpha before finishing – this is here to mitigate any rounding errors, e.g. leaving the alpha at 0.01 instead of 0 } [/code]