Encounter / Assets / Scripts / FadeInOut.cs
FadeInOut.cs
Raw
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Handles fade in and fade out functionalities
/// </summary>
public class FadeInOut : MonoBehaviour
{
    [SerializeField] private CanvasGroup canvasGroupElement;
    [SerializeField] private float timeDelay;
    [SerializeField][Tooltip("Fade from Black to Normal")] private bool fadeIn;
    [SerializeField][Tooltip("Fade from Normal to Black")] private bool fadeOut;

    private float _timeDelay;
    private bool completeTransition;

    private void Awake()
    {
        if (fadeIn)
            canvasGroupElement.alpha = 0.0f;
        else
            canvasGroupElement.alpha = 1.0f;

        _timeDelay = timeDelay;
    }

    private void Update()
    {
        if (_timeDelay > 0.0f)
        {
            _timeDelay -= Time.deltaTime;
            return;
        }

        // Fade In
        if (fadeIn && !completeTransition)
        {
            canvasGroupElement.alpha += .01f;

            if (canvasGroupElement.alpha >= 1.0f)
                completeTransition = true;
        }
        // Fade Out
        else if (!completeTransition)
        {
            canvasGroupElement.alpha -= .01f;

            if (canvasGroupElement.alpha <= 0.0f)
                completeTransition = true;
        }

        if (completeTransition)
            this.enabled = false;
    }
}