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

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 *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504