- Home /
Time.deltaTime making color lerp appear fast, but won't reach 1
I'm scripting in C# and having an issue with a color lerp. I set up an object to fade out with Time.deltaTime (I wanted the user to be able to set the fadeDuration in seconds, for example, 5), it fades out smoothly, but much too quickly, and when I check the fadeTimer, it's still crawling up at a tiny fraction of 1, which doesn't seem to make sense. Does anyone know how I can make the duration more accurate? I want to destroy this thing when the timer reaches > 1 which isn't happening with this code I've got.
void Update ()
{
if (startFade) // fade enabled
{
print (fadeTimer);
if (fadeTimer < 1)
{
renderer.material.color = Color.Lerp (renderer.material.color, Color.clear, fadeTimer);
fadeTimer += Time.deltaTime / fadeDuration; // advance timer by fractions
}
else
{
Destroy (gameObject); // once lerp is done (timer = 1), delete object
}
}
}
Answer by whydoidoit · Apr 20, 2013 at 11:27 AM
Your problem is that you are lerping from the already lerped colour. For the effect you are looking for you need to store the original colour when the lerp starts and continue to Lerp from that. The way you have it now:
Lets say the orginal colour is red, and we'll ignore the other components:
The first time you call Lerp the value of red assume a value between 1 and 0 - let's say it goes 1/8 the way, so now the value is 0.875 - next time around you are no longer lerping between 1 and 0, you are now lerping between 0.875 and 0 so the same 1/8 the way would have a much greater effect (we are now 1/4 the way there) than the first step and the value would become 0.66 etc etc
If fadeDuration isn't tiny and isn't being modified I can't work out why your timer doesn't reach 1 - I'm guessing you've set fadeDuration to a long time to make the effect closer to what you wanted?
His issue seems to be with fadeTimer but not the color. The if checks if fadeTimer is under 1 so there should be a time when fadeTimer turns out to be more than one inside the if to get the if false on next update. For some reasons, my trial works but his goes wrong somewhere...
$$anonymous$$y thought is that it's fading so fast that he's set the value of fadeDuration to be very long - the image is long gone, but the timer hasn't reached one yet.
Oooh I think I see now. The OP expects to reach transparency only at the end of the Lerp when it is already invisible way before. So yep @Clover$$anonymous$$itsune, your object is already almost invisible when you are about 0.1.
Gah! I've learned from that mistake before-- can't believe I overlooked that. :/