UnityGameProjectsCode / Rise2Point0Game / Tools / FadeInOrOut.cs
FadeInOrOut.cs
Raw
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class FadeInOrOut : MonoBehaviour
{
    //on start, wait for a command to fade in or out.
    //once command is given, begin and finish fade.
    //once finished, wait for a new fade command.
    //on starting a new fade, reset values to match start of fade.


    [Header("General Values")]

    [Tooltip("Determines the speed at which the fade travels from the starting alpha to the target alpha.")]
    [Range(0f, 2f)]
    public float fadeSpeed;

    private bool movementComplete;
    private float startTime, journeyLength;
    private float startingAlpha = 1, targetAlpha = 0;
    private float alphaBounds = 0.01f;
    SpriteRenderer spriteTarget;
    Image imageTarget;
    Text textTarget;
    TextMeshProUGUI tmpTextTarget;
    [Space]

    [Header("Fade In/Fade Out")]
    [Tooltip("True = The fade will start at an alpha of 0 and travel to the target alpha. False = The fade will start at an alpha of 1 and travel to the target alpha.")]
    public bool fadeIn; //if false, default is fade out

    [Header("Disable Object")]
    [Tooltip("When enabled, the game object associated with this script will be turned off after the fade is complete.")]
    public bool disableObjectAfterFade;
    [Space]

    [Header("Custom Alpha")]
    [Tooltip("When enabled, the specific alpha value will be used in place of the default target alpha value of 1 or 0.")]
    public bool specificAlphaTarget;
    [Tooltip("This value replaces the default alpha values of 1 or 0 when in use.")]
    [Range(0f, 1f)]
    public float specificAlpha;
    [Space]

    [Tooltip("This value determines the size of the high and low bounds.")]
    [Range(0f, 0.10f)]
    public float boundsSize;
    [Space]

    [Header("Input")]
    [Tooltip("When enabled, the fade will not start until the user presses a key.")]
    public bool waitForInput;
    private bool gotInput;
    [Space]

    [Header("Fade Wait")]
    [Tooltip("When enabled, the fade will wait for a set amount of time, using the totalWaitTime variable, before begining to fade.")]
    public bool waitBeforeFading;
    private bool waitComplete;
    [Tooltip("The amount of time that will be waited before fading.")]
    public float totalWaitTime;
    private float currentWaitTime;

    [Header("Trigger Wait")]
    [Tooltip("When enabled, the fade will not start until a method is called to start the fade.")]
    public bool waitForMethodCall;
    private bool methodCalled;

    private void Start()
    {
        alphaBounds = 0.0f + boundsSize;

        if (fadeIn)
        {
            startingAlpha = 0;
            targetAlpha = 1;

            alphaBounds = 1.0f - boundsSize;
        }

        if (specificAlphaTarget)
        {
            targetAlpha = specificAlpha;

            if (fadeIn)
                alphaBounds = specificAlpha - boundsSize;
            else
                alphaBounds = specificAlpha + boundsSize;
        }

        //can be a sprite, image, or text
        if (GetComponent<SpriteRenderer>())
        {
            spriteTarget = GetComponent<SpriteRenderer>();
            spriteTarget.color = new Color(spriteTarget.color.r, spriteTarget.color.g, spriteTarget.color.b, startingAlpha);
        }
        else if (GetComponent<Image>())
        {
            imageTarget = GetComponent<Image>();
            imageTarget.color = new Color(imageTarget.color.r, imageTarget.color.g, imageTarget.color.b, startingAlpha);
        }
        else if (GetComponent<Text>())
        {
            textTarget = GetComponent<Text>();
            textTarget.color = new Color(textTarget.color.r, textTarget.color.g, textTarget.color.b, startingAlpha);
        }
        else if (GetComponent<TextMeshProUGUI>())
        {
            tmpTextTarget = GetComponent<TextMeshProUGUI>();
            tmpTextTarget.color = new Color(tmpTextTarget.color.r, tmpTextTarget.color.g, tmpTextTarget.color.b, startingAlpha);
        }

        startTime = Time.time;
        journeyLength = 1;
    }

    private void FixedUpdate()
    {
        if (!movementComplete)
        {
            if (waitForInput && !gotInput)
            {
                if (Input.anyKeyDown)
                {
                    gotInput = true;
                    startTime = Time.time;
                }
                else
                    return;
            }

            if (waitBeforeFading && !waitComplete)
            {
                currentWaitTime += Time.fixedDeltaTime;

                if (currentWaitTime >= totalWaitTime)
                {
                    waitComplete = true;
                    startTime = Time.time;
                }
            }
            else
            {
                if (waitForMethodCall)
                {
                    if (!methodCalled)
                        return;
                }

                float distCovered = (Time.time - startTime) * fadeSpeed;
                float fracJourney = distCovered / journeyLength;

                if (spriteTarget != null)
                {
                    spriteTarget.color = new Color(spriteTarget.color.r, spriteTarget.color.g, spriteTarget.color.b, Mathf.LerpUnclamped(startingAlpha, targetAlpha, fracJourney));

                    if ((spriteTarget.color.a <= alphaBounds && !fadeIn) || (spriteTarget.color.a >= alphaBounds && fadeIn))
                    {
                        movementComplete = true;
                        if (disableObjectAfterFade)
                            gameObject.SetActive(false);
                    }
                }
                else if (imageTarget != null)
                {
                    imageTarget.color = new Color(imageTarget.color.r, imageTarget.color.g, imageTarget.color.b, Mathf.LerpUnclamped(startingAlpha, targetAlpha, fracJourney));

                    if ((imageTarget.color.a <= alphaBounds && !fadeIn) || (imageTarget.color.a >= alphaBounds && fadeIn))
                    {
                        movementComplete = true;
                        if (disableObjectAfterFade)
                            gameObject.SetActive(false);
                    }
                }
                else if (textTarget != null)
                {
                    textTarget.color = new Color(textTarget.color.r, textTarget.color.g, textTarget.color.b, Mathf.LerpUnclamped(startingAlpha, targetAlpha, fracJourney));

                    if ((textTarget.color.a <= alphaBounds && !fadeIn) || (textTarget.color.a >= alphaBounds && fadeIn))
                    {
                        movementComplete = true;
                        if (disableObjectAfterFade)
                            gameObject.SetActive(false);
                    }
                }
                else if (tmpTextTarget != null)
                {
                    tmpTextTarget.color = new Color(tmpTextTarget.color.r, tmpTextTarget.color.g, tmpTextTarget.color.b, Mathf.LerpUnclamped(startingAlpha, targetAlpha, fracJourney));

                    if ((tmpTextTarget.color.a <= alphaBounds && !fadeIn) || (tmpTextTarget.color.a >= alphaBounds && fadeIn))
                    {
                        movementComplete = true;
                        if (disableObjectAfterFade)
                            gameObject.SetActive(false);
                    }
                }
            }
        }
    }

    public void ResetFade()
    {
        startTime = Time.time;
        movementComplete = false;
        methodCalled = false;

        if (waitBeforeFading)
        {
            waitComplete = false;
            currentWaitTime = 0.0f;
        }

        if (disableObjectAfterFade)
        {
            gameObject.SetActive(true);
        }

        if (fadeIn)
        {
            startingAlpha = 0;
            targetAlpha = 1;

            alphaBounds = 1.0f - boundsSize;
        }
        else
        {
            startingAlpha = 1;
            targetAlpha = 0;

            alphaBounds = 0.0f + boundsSize;
        }
    }

    public void StartFade()
    {
        methodCalled = true;
    }

    public bool GetFadeState()
    {
        return movementComplete;
    }
}