How can I fade in/out a canvas group alpha color with duration time ?

Don’t use Mathf.Lerp(). Use Mathf.MoveTowards().

And definitely DO NOT USE COROUTINES (see my post above).

make some member variables:

private float desiredAlpha;
private float currentAlpha;

The work:

void Update()
{
  currentAlpha = Mathf.MoveTowards( currentAlpha, desiredAlpha, 2.0f * Time.deltaTime);
}

Now, wherever you need to set fadedness of any object, use currentAlpha.

colorProperty.a = currentAlpha;

When you want to change fadedness, only set desiredAlpha equal to 0 or 1.

desiredAlpha = 1.0f;

That’s it, you’re done. It’s actually that simple.

10 Likes