Bug with alpha?

Hi guys.
I need to make a fade-out effect for my label.
Here is my code:

using UnityEngine;
using UnityEngine.UI;

public class TweenAlpha : MonoBehaviour
{
    public float Speed;
    private Text Label;
    private float alpha;
    private Color color;

    /* -------- */

    void Start()
    {
        Label = GetComponent<Text>();
        if(Label == null)
            this.enabled = false;
        color = Label.color;
    }

    /* -------- */

    void Update()
    {
        alpha += Time.deltaTime / Speed;
        color.a = alpha;

        Label.color = color;
    }

    /* -------- */
}

For example:
Speed = 3 (Fade-in effect)
Speed = -3 (Fade-out effect).

As i said i need to make a fade-out effect,but here is my problem : the alpha value of my label becomes immediately…let’s say ‘zero’.
However, fade-in effect works fine with this script.

That’s because you haven’t assigned alpha a value so it will always be initialised to zero.

Rather than using a local variable you could just do:

void Update()
{
    color.a = color.a + Time.deltaTime / Speed;
    Label.color = color;
}

There’s potentially a few other issues in that code though, like there’s no end to the fade etc…

1 Like

Thanks! It works now.

Well,this is just a test :wink: