- Home /
UI Text not changing color [C#]
I'm trying to make my text fade in and out, but it's not working. I used Debug.Log
and other methods to find out that it thought the color was changing and said it was, but the color itself would never actually change. Everything else in the coroutine works perfectly.
Here's my code:
public void TriggerText(string textToTrigger)
{
GetComponent<Text>().text = textToTrigger;
transform.Find("ExtraTrans").GetComponent<Text>().text = textToTrigger;
StartCoroutine(FadeTextToFullAlpha(0.5f, GetComponent<Text>()));
StartCoroutine(FadeTextToFullAlpha(0.5f, transform.Find("ExtraTrans").GetComponent<Text>()));
}
public IEnumerator FadeTextToFullAlpha(float t, Text i)
{
i.color = new Color(i.color.r, i.color.g, i.color.b, 0f);
while (i.color.a < 1.0f)
{
i.color = new Color(i.color.r, i.color.g, i.color.b, i.color.a + (Time.deltaTime / t));
yield return null;
}
}
public IEnumerator FadeTextToZeroAlpha(float t, Text i)
{
i.color = new Color(i.color.r, i.color.g, i.color.b, 1f);
while (i.color.a > 0.0f)
{
i.color = new Color(i.color.r, i.color.g, i.color.b, i.color.a - (Time.deltaTime / t));
yield return null;
}
}
ExtraTrans is a GameObject to give the text more default opacity (like a value of 2 or 510.)
Answer by kaarloew · Dec 12, 2018 at 07:48 AM
If you aren't trying to "learn the ropes" then it is easier to use some existing tween library for the fades, e.g. Zestkit https://github.com/prime31/ZestKit
And that FadeTextToZeroAlpha method isn't called anywhere.
I hadn't called it because I was testing FadeTextToFullAlpha first.
Answer by kaosermail · Dec 12, 2018 at 02:29 PM
First, you shouldn't do it on a while, becouse it will be entirely resolved in one frame. Secondly, I think you are exiting the while in the first iteration with that yield return null.
What I would do:
Set a bool flag to true instead of the while, and create an Update method where if that bool is set to true, you do this:
i.color = new Color(i.color.r, i.color.g, i.color.b, i.color.a - (Time.deltaTime / t));
And do another if i.color.a == 1 to set the flag to false.