Fading a UI Image alpha to zero only works once.

After looking at some previous answers I came up with this co routine hoping to have a UI white screen “flash” for the appropriate of time. And it works as expected once, but will not work again;

   public IEnumerator LerpWhiteScreen (float duration)
    {
        Color temp = whiteScreen.color;
        temp.a = 1f;
        whiteScreen.color = temp;

        for (int i = 0; i < duration; i++)
        {
            whiteScreen.CrossFadeAlpha (0, duration, false);
            yield return null;
        }
    }
  • note since I can’t directly affect the image.color.a, I had to create a “temp color” and effect it’s alpha, then assign that value to my image. This is to have the white screen turn completely white, and then fade to 0.

SOLVED

So after doing some research and stumbling across this answer;

I have solved this problem by added the line suggested to reset the alpha back to 1;

whiteScreen.canvasRenderer.SetAlpha (1f);

Another thing I have learned here is that the object’s alpha needs to be set at 1, and then you can shut it off at runtime in Start ().

So now my code looks like this;

    void Start ()
    {
        whiteScreen.canvasRenderer.SetAlpha (0f);
    }

void LerpWhiteScreen (float duration)
{
    whiteScreen.canvasRenderer.SetAlpha (1f);
    whiteScreen.CrossFadeAlpha (0.0f, duration, true);
}

This now works as expected! Thanks everyone who helped me get to the solution!

Do not use a coroutine.

just

img.color = new Vector4(1f,1f,1f,1f);
img.CrossFadeAlpha(0.0f, 1.0f, true);

CrossFadeAlpha do the work. It is a tween. @Rick74

Its giving you trouble beacuse there is actually 2 transparency values in UI elements.

There is the BaseColor that you access in the unity inspector and there is an internal one accessed only through the CanvasRenderer.

If you want to use CrossFadeAlpha or CrossFadeColor you will have to change the UI element properties using the CanvasRender component.

whiteScreen.canvasRenderer.SetAlpha (1f);
whiteScreen.canvasRenderer.SetColor(Color.clear);