Part of these game systems:
Screen Fader
Simple screen fade-in/fade-out with configurable color and duration. Great for scene transitions.
How to Use
1
Create a UI Canvas with a full-screen Image
2
Attach ScreenFader and assign the Image
3
FadeIn: ScreenFader.Instance.FadeIn()
4
FadeOut: ScreenFader.Instance.FadeOut()
5
Scene transition: ScreenFader.Instance.FadeOutAndIn(0.5f, () => LoadScene())
Source Code
C#
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScreenFader : MonoBehaviour
{
public static ScreenFader Instance { get; private set; }
[SerializeField] private Image fadeImage;
[SerializeField] private float defaultDuration = 0.5f;
[SerializeField] private Color fadeColor = Color.black;
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
fadeImage.color = fadeColor;
fadeImage.raycastTarget = false;
}
public Coroutine FadeIn(float duration = -1f)
{
return StartCoroutine(Fade(1f, 0f, duration < 0 ? defaultDuration : duration));
}
public Coroutine FadeOut(float duration = -1f)
{
return StartCoroutine(Fade(0f, 1f, duration < 0 ? defaultDuration : duration));
}
public Coroutine FadeOutAndIn(float duration = -1f, System.Action onMiddle = null)
{
float d = duration < 0 ? defaultDuration : duration;
return StartCoroutine(FadeOutInRoutine(d, onMiddle));
}
private IEnumerator Fade(float from, float to, float duration)
{
fadeImage.raycastTarget = true;
float elapsed = 0f;
while (elapsed < duration)
{
elapsed += Time.unscaledDeltaTime;
float alpha = Mathf.Lerp(from, to, elapsed / duration);
fadeImage.color = new Color(fadeColor.r, fadeColor.g, fadeColor.b, alpha);
yield return null;
}
fadeImage.color = new Color(fadeColor.r, fadeColor.g, fadeColor.b, to);
fadeImage.raycastTarget = to > 0.5f;
}
private IEnumerator FadeOutInRoutine(float halfDuration, System.Action onMiddle)
{
yield return Fade(0f, 1f, halfDuration);
onMiddle?.Invoke();
yield return Fade(1f, 0f, halfDuration);
}
}