Simple C# script to fade in/out UI Image.

Content not available.
Please allow cookies by clicking Accept on the banner

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

//Fades in or out UI Image

public class FadeInOutImage : MonoBehaviour {
    [SerializeField] private Image imageToUse;
    [SerializeField] private bool useThisImage = false;

    [Tooltip("false - Fades Out, true = Fades In")]
    [SerializeField] private bool fadeIn = false;
    [SerializeField] private bool fadeOnStart = false;

    [SerializeField] private float timeMultiplier;

    private void Start()
    {
        if (useThisImage)
        {
            imageToUse = GetComponent<Image>();
        }

        if (fadeOnStart)
        {
            if (fadeIn)
            {
                StartCoroutine(FadeInText(timeMultiplier, imageToUse));
            }
            else
            {
                StartCoroutine(FadeOutText(timeMultiplier, imageToUse));
            }
        }
    }

    private IEnumerator FadeInText(float timeSpeed, Image text)
    {
        text.color = new Color(text.color.r, text.color.g, text.color.b, 0);

        while (text.color.a < 1.0f)
        {
            text.color = new Color(text.color.r, text.color.g, text.color.b, text.color.a + (Time.deltaTime * timeSpeed));
            yield return null;
        }
    }

    private IEnumerator FadeOutText(float timeSpeed, Image text)
    {
        text.color = new Color(text.color.r, text.color.g, text.color.b, 1);

        while (text.color.a > 0.0f)
        {
            text.color = new Color(text.color.r, text.color.g, text.color.b, text.color.a - (Time.deltaTime * timeSpeed));
            yield return null;
        }
    }

    public void FadeInText(float timeSpeed = -1.0f)
    {
        if (timeSpeed <= 0.0f)
        {
            timeSpeed = timeMultiplier;
        }

        StartCoroutine(FadeInText(timeSpeed, imageToUse));
    }

    public void FadeOutText(float timeSpeed = -1.0f)
    {
        if (timeSpeed <= 0.0f)
        {
            timeSpeed = timeMultiplier;
        }

        StartCoroutine(FadeOutText(timeSpeed, imageToUse));
    }
}

 

Unity UI C# Fade In/Out Image
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close