Encounter / Assets / Scripts / CameraManager.cs
CameraManager.cs
Raw
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

public class CameraManager : MonoBehaviour
{
    public static CameraManager Instance { get; private set; }

    [Header("Canvas Elements")]
    [SerializeField] private Image darkeningPanel;

    [Header("Attributes")]
    [SerializeField] private float darkeningVolume = 3f;
    [SerializeField] private float darkenSpeed = 1.5f;

    private bool animatingInProcess;

    private void Awake()
    {
        Instance = this;
    }

    public async Task DarkenScreen()
    {
        StartCoroutine(ChangeAlphaOfScreen(true));

        while (animatingInProcess)
            await Task.Yield();
    }

    public async Task LightenScreen() 
    {
        StartCoroutine(ChangeAlphaOfScreen(false));

        while (animatingInProcess)
            await Task.Yield();
    } 

    private IEnumerator ChangeAlphaOfScreen(bool isDarkening)
    {
        animatingInProcess = true;
        Color colorAttribute = darkeningPanel.color;

        float destValue = isDarkening ? 1f : 0f;
        while (colorAttribute.a != destValue)
        {
            if (isDarkening)
                colorAttribute = new Color(colorAttribute.r, colorAttribute.g, colorAttribute.b, colorAttribute.a + (darkenSpeed * darkeningVolume));
            else
                colorAttribute = new Color(colorAttribute.r, colorAttribute.g, colorAttribute.b, colorAttribute.a - (darkenSpeed * darkeningVolume));

            darkeningPanel.color = colorAttribute;
            yield return new WaitForSeconds(.05f);
        }

        animatingInProcess = false;
    }
}