Cannot seem to get Color.Lerp to work on an image in a canvas.

I’ve been struggling with this issue for some time now. I simply want a lerp between the alpha of an image (from 0 to 1), but the transition never completes, no matter where I execute the lerp. Here is a simplified version of what I’m trying :


public Image redUI;
public bool hit;
Color alphaZero = new Color(1f, 1f, 1f, 0f);
Color alpha = new Color(1f, 1f, 1f, 1f);

void FixedUpdate () {

if(hit)
{

redUI.color = Color.Lerp(alphaZero, alpha, .2f);

}

}

Is hit remaining true the whole time or does it get reset at some point to false?

Edit: Nevermind, your lerp is only going .2 so it will never complete.

No matter what value I put in the “t” of the lerp no transition ever happens. And the hit boolean stays true for long enough to let the interpolation happen.

You need to pass in a changing value of 0 - 1 for t.

public Image redUI;
public float transTime = 2.0f;
public bool hit;
Color alphaZero = new Color(1f, 1f, 1f, 0f);
float timePassed = 0.0f;

void FixedUpdate()
{
     if (hit && timePassed < transTime)
     {
          timePassed += Time.fixedDeltaTime;
          redUI.color = Color.Lerp(alphaZero, Color.white, timePassed / transTime);
     }
}
1 Like

Thank you for the reply, I’ll try this out tomorrow. What I find weird is that I’ve never needed to gradually increase the value of “t” in order for the lerp to work in other situations using Vector3.Lerp or Mathf.Lerp, hence my confusion at first. But I might be wrong, I’ll take another look at my documentation.

I have seen tutorials use Lerp wrong that could be the cause of the confusion.

An example of how not to use lerp:

transform.position = Vector3.Lerp(transform.position, targetPosition, 0.1f);

This does “work” but it never really finishes and will continue to lerp almost indefinitely(if we had unlimited precision it would.)

That’s interesting. That means I’ve been using lerp wrong this whole time. Thanks for the explanation.

The bit of code you showed me works perfectly. Thanks for your help!

1 Like