How to make text fade out in Unity

Fade in and fade out are very elegant looking features in text animation. Unfortunately, Unity’s inbuilt UI system doesn’t have this option by default. You need to do this using code.

In this tutorial, we will see how to fade in and fade out the text element in Unity. I am using Unity 2021.1.13 for this tutorial.

The idea behind this technique is to control the alpha value of the text element to make it look like it is fading away.

Texting fading out

Add a text element to your scene.

Create an empty game object and name it effects.

Add a new script called fade_out to effects.

Click edit script to open it in script editor.

Copy and paste the code below.

Fade out script

using UnityEngine;
using UnityEngine.UI;

public class fade_out : MonoBehaviour
{
    public Text tex;
    Color col;
    void Start()
    {
        col=tex.color;
    }

    // Update is called once per frame
    void Update()
    {
        if(col.a>0)
        {
            col.a-=Time.deltaTime;
            tex.color=col;
        }
        
    }
}

Save and return to Unity editor.

Drag and drop the text that needs to fade out to the tex variable.

You can make some minor modifications to the code to make the text fade in. Here is the code to make the text fade in.

Fade in script

using UnityEngine;
using UnityEngine.UI;

public class fade_out : MonoBehaviour
{
    public Text tex;
    Color col;
    void Start()
    {
        col=tex.color;
        col.a=0;
        tex.color=col;
    }

    // Update is called once per frame
    void Update()
    {
        if(col.a<256)
        {
            col.a+=Time.deltaTime;
            tex.color=col;
        }
        
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading