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

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 Text

public class FadeInOutText : MonoBehaviour {
    [SerializeField] private Text textToUse;
    [SerializeField] private bool useThisText = 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 (useThisText)
        {
            textToUse = GetComponent<Text>();
        }

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

    private IEnumerator FadeInText(float timeSpeed, Text 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, Text 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, textToUse));
    }

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

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

 

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

One thought on “Unity UI C# Fade In/Out Text

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