Issues with fading text.

Hi, this is my first time posting here but I was wondering if someone would be able to help me with an issue I’m having with my code. Whenever I run this code, which is meant to slowly fade text by reducing its alpha, the alpha instantly sets to zero. I’m not sure if this is because the fade is happening to fast or there is an error in my code. Here is my code:

public void Fadeout (int Player, string sign, int value, int position) {
		PlayerOneSavingsModIndicator.color = new Color (PlayerOneSavingsModIndicator.color.r, PlayerOneSavingsModIndicator.color.g, PlayerOneSavingsModIndicator.color.b, 1f);
		if (Player == 0) {
			if (position == 1) {
				PlayerOneSavingsModIndicator.text = sign + value;
				if (sign == "-") {
					PlayerOneSavingsModIndicator.color = Color.red;
				} else if (sign == "+") {
					PlayerOneSavingsModIndicator.color = Color.green;
				}

				while (PlayerOneSavingsModIndicator.color.a > 0.0f) {
					PlayerOneSavingsModIndicator.color = new Color (PlayerOneSavingsModIndicator.color.r, PlayerOneSavingsModIndicator.color.g, PlayerOneSavingsModIndicator.color.b, PlayerOneSavingsModIndicator.color.a - (Time.deltaTime / 10));
				}

			} else if (position == 2) {
			}
		} else if (Player == 1) {
		} else if (Player == 2) {
		} else if (Player == 3) {
		}

Any help would be greatly appreciated. Thank you.

Hello there,

There are easier ways to fade Text elements in an out, like myText.CrossFadeAlpha().

But if you want to have more control over the process, you can use something like this:

///target = the Text component we want to fade
    ///duration - How long the fade should take
    ///targetAlpha - What should the alpha be at the end
    ///[Optional] unscaledTime - Set to true if you want the fade to happen independently of timeScale
    private IEnumerator FadeText(UnityEngine.UI.Text target, float duration, float targetAlpha, bool unscaledTime = false)
    {
        float timer = 0.0f;
        float startAlpha = target.color.a;

        // Start Fade
        while (timer < duration)
        {
            // 
            timer += unscaledTime ? Time.unscaledDeltaTime : Time.deltaTime;
            float t = timer / duration;
            t = t * t * t * (t * (6f * t - 15f) + 10f);
            float curTargetAlpha = Mathf.Lerp(startAlpha, targetAlpha, t);
            Color targetColor = new Color(target.color.r, target.color.g, target.color.b, curTargetAlpha);
            target.color = targetColor;

            yield return null;
        }

        // Fade has finished
        yield return null;
    }

You can call is with StartCoroutine(FadeText(myText, 2.0f, 0.0f));.


Hope that helps!

Cheers,

~LegendBacon