Fading UI Text object causes all objects in UI canvas to fade

Hi,

I have a UI Text label for the words “Game Over”. I would like to show and fade it out after the game finishes. I can use a coroutine to fade out the text. However, my problem is that it fades the entire canvas. When I stop the game, the Canvas remains faded out unless I reset the workspace by reloading.

Here’s the code I’m using to fade out the text:

public IEnumerator FadeOut()
    {
        yield return new WaitForSeconds(1.5f);
        Text text = gameObject.GetComponent<Text>();
        for (float i = 1; i >= 0; i -= 0.1f)
        {
            Color c = text.material.color;
            c.a = i;
            text.material.color = c;
            yield return new WaitForSeconds(0.1f);
        }
        gameObject.SetActive(false);
     
    }

I’ve never transacted against the material the way you are doing.

Usually I just do it this way:

Color c = text.color;
c.a = i;
text.color = c;

Pretty sure that will only affect that one text object.

In the future, if you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: Using code tags properly

1 Like

That did the trick. Thank you! I’m new to this forum so thank you for mentioning the code formatting option. I’ve updated the original just to be in line :slight_smile:

I do wonder why my original code would affect the whole of the UI Canvas items. It did seem like it was intentional and frankly would work for some folks looking to fade an entire canvas. Still very new here and appreciate the super fast response.

1 Like

As a guess, I would think the same default material is shared throughout the UI, and your twiddling it made it change all instances perhaps? It would be easy to iterate all your visual things and check the .GetInstanceID() off each material, see if it is indeed shared.

I think there’s better ways to do this, such as with a CanvasGroup. Otherwise the change might be global to the whole scene or screen or maybe even persist through multiple scenes!

You’re welcome! Jump right in… Unity is tons of fun to learn and mess around with!

Just so you know then that the 2D forums isn’t for UI, that has a dedicated forum here.