using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIFade : Singleton { [SerializeField] private Image fadeScreen; // UI Image used for the fade effect [SerializeField] private float fadeSpeed = 1f; // Speed at which the fade effect occurs private IEnumerator fadeRoutine; // Coroutine reference for the fade effect // Starts a fade to black (full opacity) public void FadeToBlack() { if (fadeRoutine != null) { StopCoroutine(fadeRoutine); // Stop any ongoing fade coroutine } fadeRoutine = FadeRoutine(1); // Set target alpha to 1 (black) StartCoroutine(fadeRoutine); } // Starts a fade to clear (no opacity) public void FadeToClear() { if (fadeRoutine != null) { StopCoroutine(fadeRoutine); // Stop any ongoing fade coroutine } fadeRoutine = FadeRoutine(0); // Set target alpha to 0 (clear) StartCoroutine(fadeRoutine); } // Coroutine to smoothly transition the alpha of the fade screen private IEnumerator FadeRoutine(float targetAlpha) { while (!Mathf.Approximately(fadeScreen.color.a, targetAlpha)) // Continue until target alpha is reached { // Gradually move alpha towards the target alpha value float alpha = Mathf.MoveTowards(fadeScreen.color.a, targetAlpha, fadeSpeed * Time.deltaTime); fadeScreen.color = new Color(fadeScreen.color.r, fadeScreen.color.g, fadeScreen.color.b, alpha); yield return null; // Wait until the next frame } } }